我正在尝试创建一个动画,该动画拍摄页面上任何位置的图像,然后将其移动到中间,同时将其调整为浏览器窗口的整个宽度。我的解决方案有效,但是其中有些卡顿/跳动,我无法真正解释。已经有人尝试创建类似的动画了吗? 编辑:我注意到,口吃问题似乎仅出现在macOS Safari中。在其他浏览器中,此动画似乎运行得非常流畅。
这是我的js代码:
function getWindowWidth() {
return document.documentElement.clientWidth
}
function getWindowHeight() {
return document.documentElement.clientHeight;
}
//at the moment this is hacky and only supports one image to be enlarged
let en_img_left = null;
let en_img_top = null;
function enlargeImage(img) {
let boundingClientRect = img.getBoundingClientRect();
img.style.position = "fixed";
en_img_top = boundingClientRect.y + "px";
img.style.top = en_img_top;
en_img_left = boundingClientRect.x + "px";
img.style.left = en_img_left;
img.style.width = boundingClientRect.width + "px";
img.style.zIndex = "1000";
setTimeout(function() {
img.style.transition = "1s ease-in-out";
setTimeout(function() {
let scaleFactor = getWindowWidth() / boundingClientRect.width;
img.style.transform = "scale(" + scaleFactor + ")";
img.style.left = getWindowWidth() / 2 - (boundingClientRect.width / 2) + "px";
img.style.top = getWindowHeight() / 2 - boundingClientRect.height / 2 + "px";
}, 1);
}, 1);
return img;
}
function delargeImage(img) { //sorry for the function name
img.style.transition = "1s ease-in-out";
setTimeout(function() {
img.style.transform = "scale(1)";
img.style.left = en_img_left;
img.style.top = en_img_top;
}, 1);
return img;
}
示例HTML + CSS代码,但可以是网站上ID为ID的任何图像:
HTML:
<div class="container">
<img id="example" style="width: 100%" src="https://images.pexels.com/photos/1361815/pexels-photo-1361815.jpeg?cs=srgb&dl=blur-bokeh-close-up-1361815.jpg&fm=jpg">
</div>
CSS:
.container {
width: 200px;
}
我还做了一个jsfiddle,很好地显示了口吃问题: https://jsfiddle.net/robske_110/vhz5Ln4o/11/
答案 0 :(得分:0)
您没有使用CSS动画或过渡效果!
在您的示例中,动画本身是通过JavaScript执行的。代替在JS中计算动画的每个步骤并在每次迭代中设置新的CSS属性,您应该使用所需的开始状态和结束状态来设置CSS动画,或者定义应该转换的属性。这样,动画在过渡时应该看起来很平滑。
您使用CSS过渡的示例(没有任何JS代码):
.container {
width: 200px;
transition: width ease-in 1s;
}
.container:hover {
width: 80vw;
}
.container img {
width: 100%;
}
<div class="container">
<img id="example" src="https://images.pexels.com/photos/1361815/pexels-photo-1361815.jpeg?cs=srgb&dl=blur-bokeh-close-up-1361815.jpg&fm=jpg">
</div>