js 移动端 图片放大预览+拖拽
在移动端实现图片放大预览和拖拽功能,可以使用HTML5和CSS3结合JavaScript来完成。以下是一个简单的实现示例:
HTML部分:
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
#myImg {
width: 100%;
height: auto;
cursor: pointer;
transition: transform 0.2s ease;
}
#myImg:hover {
transform: scale(1.1);
}
#myModal {
display: none;
position: fixed;
z-index: 1;
padding-top: 100px;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgb(0,0,0);
background-color: rgba(0,0,0,0.9);
}
#img01 {
margin: auto;
display: block;
width: 80%;
max-width: 700px;
}
.modal-content {
margin: auto;
display: block;
width: 80%;
max-width: 700px;
}
.close {
position: absolute;
top: 15px;
right: 35px;
color: #f1f1f1;
font-size: 40px;
font-weight: bold;
transition: 0.3s;
}
.close:hover,
.close:focus {
color: #bbb;
text-decoration: none;
cursor: pointer;
}
.draggable {
width: 100%;
height: 100vh;
touch-action: none;
}
</style>
</head>
<body>
<img id="myImg" class="draggable" src="path_to_image/image.jpg" alt="Image">
<div id="myModal" class="modal">
<span class="close">×</span>
<img class="modal-content" id="img01">
</div>
<script>
// 图片点击事件
var modal = document.getElementById("myModal");
var img = document.getElementById("myImg");
var img01 = document.getElementById("img01");
var span = document.getElementsByClassName("close")[0];
img.onclick = function() {
modal.style.display = "block";
img01.src = this.src;
}
span.onclick = function() {
modal.style.display = "none";
}
// 实现移动端图片拖拽功能
var draggable = document.querySelector('.draggable');
var active = false;
var currentX;
var currentY;
var initialX;
var initialY;
var xOffset = 0;
var yOffset = 0;
function dragStart(e) {
if (e.type === "touchstart") {
initialX = e.touches[0].clientX - xOffset;
initialY = e.touches[0].clientY - yOffset;
} else {
initialX = e.clientX - xOffset;
initialY = e.clientY - yOffset;
}
if (e.target === draggable) {
active = true;
}
}
function dragEnd(e) {
initialX = currentX;
initialY = currentY;
active = false;
}
function drag
评论已关闭