javascript - 用于在 Safari 中放大图像的 Stuttery CSS 动画

标签 javascript html css css-animations web-animations

我正在尝试创建一个动画,它获取页面上任意位置的图像并将其移动到中间,同时将其调整为浏览器窗口的全宽。我的解决方案有效,但其中有一些断断续续/跳跃,我无法真正解释。有没有人已经尝试过制作类似的动画? 编辑:我注意到卡顿问题似乎只出现在 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 的任何图像:

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/

最佳答案

您没有使用 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>

关于javascript - 用于在 Safari 中放大图像的 Stuttery CSS 动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52036907/

相关文章:

javascript - 在多个选择器上设置属性

multithreading - 没有 web worker 的 Javascript 后台处理?

html - 无法让 CSS 划分相互匹配,即使它们是相同的

javascript - 是否可以使用 css3 缩放仅缩放容器大小(不缩放内容)?

css - Phonegap,480x720、480x800 和 480x854 的 css 样式问题

javascript - 使用jQuery为同一类的不同div中的特定元素添加悬停效果

php - jQueryUI 自动完成功能不起作用

javascript - 使用不适用于 Bootstrap 的样式打印 HTML div

javascript - 是否可以检测浏览器选项卡是否正在播放音频?

html - css overlay 使背景不透明