【发布时间】:2019-01-22 10:29:06
【问题描述】:
对于我正在制作的网站,我制作了一张自定义地图,这是一张图片。不过,对于这个网站,我需要使这个图像可缩放,并在特定的“框”内拖动。
我用 JS 在“item”中获得了图像,这使得图像可以滚动和拖动。我使用的图像很大,因为它需要放大/缩小。
代码:
var dragItem = document.querySelector("#item");
var container = document.querySelector("#container");
var active = false;
var currentX;
var currentY;
var initialX;
var initialY;
var xOffset = 0;
var yOffset = 0;
container.addEventListener("touchstart", dragStart, false);
container.addEventListener("touchend", dragEnd, false);
container.addEventListener("touchmove", drag, false);
container.addEventListener("mousedown", dragStart, false);
container.addEventListener("mouseup", dragEnd, false);
container.addEventListener("mousemove", drag, false);
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 === dragItem) {
active = true;
}
}
function dragEnd(e) {
initialX = currentX;
initialY = currentY;
active = false;
}
function drag(e) {
if (active) {
e.preventDefault();
if (e.type === "touchmove") {
currentX = e.touches[0].clientX - initialX;
currentY = e.touches[0].clientY - initialY;
} else {
currentX = e.clientX - initialX;
currentY = e.clientY - initialY;
}
xOffset = currentX;
yOffset = currentY;
setTranslate(currentX, currentY, dragItem);
}
}
function setTranslate(xPos, yPos, el) {
el.style.transform = "translate3d(" + xPos + "px, " + yPos + "px, 0)";
}
#container {
width: 9109px;
height: 5963px;
background-color: #3ab0c9;
display: flex;
align-items: center;
justify-content: center;
overflow: hidden;
touch-action: none;
}
#item {
width: 9109px;
height: 5963px;
background-image: url("map.png");
touch-action: none;
user-select: none;
}
#item:hover {
cursor: pointer;
border-width: 20px;
}
<div id="outerContainer">
<div id="container">
<div id="item">
</div>
</div>
</div>
我只需要创建缩放按钮,但我不知道怎么做!有人能帮我吗?我只是无法让它工作......
【问题讨论】:
-
由于您使用的是图像,您可以在 setTranslate 函数中使用 scale3d(x,y,z) 来放大和缩小#item 吗?这样你就可以模仿 Scale 动画
标签: javascript html css