我有一张图片:
img {
position : absolute;
transition : 1s;
}
我通过更改其高度并使用 style.left
来缩放该图像的特定部分 img.style.height = "100%";
var width = img.clientWidth;
img.style.left = width+"px";
问题在于1s转换会使clientWidth错误,因为最终宽度是在转换完成后实现的。我不想将程序暂停1秒,但我想在高度过渡1秒后获得图像的最终宽度。
答案 0 :(得分:0)
您可以将超时设置为1秒,然后执行代码: 这是一些doc
setTimeout(function(){
img.style.height = "100%";
var width = img.clientWidth;
img.style.left = width+"px";
}, 1000);
答案 1 :(得分:0)
JavaScript具有用于转换(和动画)的事件监听器。下面的代码段提取了正确的transitionEvent(用于跨浏览器)并将其应用于元素。然后,您可以将函数绑定到过渡事件。
来源:Detect the End of CSS Animations and Transitions with Javascript
var image = document.querySelector("img"),
transitionEvent = whichTransitionEvent();
image.addEventListener("click", function() {
image.style.height = "300px";
image.addEventListener(transitionEvent, customFunction);
});
function customFunction(event) {
var width = image.clientWidth;
image.style.left = width+"px";
image.removeEventListener(transitionEvent, customFunction);
}
function whichTransitionEvent(){
var t,
el = document.createElement("fakeelement");
var transitions = {
"transition" : "transitionend",
"OTransition" : "oTransitionEnd",
"MozTransition" : "transitionend",
"WebkitTransition": "webkitTransitionEnd"
}
for (t in transitions){
if (el.style[t] !== undefined){
return transitions[t];
}
}
}
img {
position:absolute;
height: 200px;
transition: 1s;
}
<div>
<img src="https://via.placeholder.com/200x200" />
</div>
答案 2 :(得分:0)
基本上保持了图像的长宽比,因此要知道过渡后的宽度,我们可以对其进行计算。
公式为ref:
用户选择的高度*原始宽度/原始高度
document.querySelector("img").onclick = e => {
let originalImgBounds = e.target.getBoundingClientRect();
let newZoomedHeight = 300;
let newZoomedWidth = newZoomedHeight * originalImgBounds.width / originalImgBounds.height;
e.target.style.height = newZoomedHeight + "px";
e.target.style.left = newZoomedWidth + "px";
};
img {
position: absolute;
height: 200px;
left: 0;
transition: 1s;
}
<img src="https://via.placeholder.com/200x200" />