首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用于Safari中放大图像的结语CSS动画

用于Safari中放大图像的结语CSS动画
EN

Stack Overflow用户
提问于 2018-08-27 10:02:14
回答 1查看 176关注 0票数 0

我正在尝试创建一个动画,它将页面上任意位置的图像移动到中间,同时将其调整到浏览器窗口的全宽度。我的解决方案有效,但有一些口吃/跳跃,我无法真正解释。有没有人尝试创建类似的动画?编辑:我注意到口吃问题似乎只出现在macOS Safari中。在其他浏览器中,这个动画看起来非常流畅。

这是我的js代码:

代码语言:javascript
复制
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的图像:

HTML:

代码语言:javascript
复制
<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:

代码语言:javascript
复制
.container {
   width: 200px;
}

我还做了一个小提琴,很好地显示了口吃问题:110/vhz5Ln4o/11/

EN

回答 1

Stack Overflow用户

发布于 2018-08-27 10:46:41

您没有使用CSS动画或转换!

在您的示例中,动画本身是通过JavaScript执行的。与其计算JS中动画的每一步并在每次迭代中设置一个新的CSS属性,还不如用所需的开始状态和结束状态来设置CSS动画,或者定义应该转换的属性。这样,动画在过渡的时候应该看上去很流畅。

您的示例使用CSS转换(没有任何JS代码):

代码语言:javascript
复制
.container {
	width: 200px;
  transition: width ease-in 1s;
}

.container:hover {
  width: 80vw;
}

.container img {
  width: 100%;
}
代码语言:javascript
复制
<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>

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52036907

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档