用js写一个点击图片即可放大至全屏且有按钮返回的代码
时间: 2023-06-17 22:04:50 浏览: 88
你可以使用以下代码实现点击图片放大至全屏并有返回按钮的效果:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Full Screen Image</title>
<style>
body {
margin: 0;
padding: 0;
overflow: hidden;
}
#fullscreen {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.7);
display: none;
z-index: 9999;
}
#fullscreen img {
max-width: 100%;
max-height: 100%;
margin: auto;
display: block;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
#fullscreen button {
position: absolute;
top: 10px;
right: 10px;
background-color: transparent;
color: #fff;
border: none;
font-size: 24px;
cursor: pointer;
}
</style>
</head>
<body>
<img src="example.jpg" onclick="showFullScreen(this)">
<div id="fullscreen">
<button onclick="hideFullScreen()">X</button>
<img src="">
</div>
<script>
function showFullScreen(img) {
document.querySelector("#fullscreen img").src = img.src;
document.querySelector("#fullscreen").style.display = "block";
}
function hideFullScreen() {
document.querySelector("#fullscreen").style.display = "none";
}
</script>
</body>
</html>
```
在这个例子中,我们使用了 HTML、CSS 和 JavaScript 来实现图片全屏显示的效果。当用户点击图片时,会触发 `showFullScreen` 函数,该函数会将当前点击的图片的 `src` 属性值赋给全屏显示的 `img` 标签,并将全屏显示的 `div` 显示出来。在全屏显示的 `div` 中,我们使用了一个 `button` 元素来提供返回功能,当用户点击该按钮时,会触发 `hideFullScreen` 函数,该函数会将全屏显示的 `div` 隐藏起来。