首页 > 解决方案 > 我想要一个基于滚动位置的 IMG 淡入淡出,适用于桌面,但移动设备上的滚动位置始终为“0”。

问题描述

我在这里找到了这段代码:https ://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onscroll3虽然当我在我的移动浏览器中输入 URL 时它可以工作,但当我预览文件时它不起作用我的代码编辑器(目前使用 Dreamweaver)。

我尝试过应用溢出:滚动到 HTML 和正文,我也尝试过使用 scrollTop、scrollY,并将页面偏移量应用于变量,例如 var scrollY = window.pageYOffset; 但似乎无法让它工作。我很感激任何帮助!我可以看到可以根据移动屏幕位置触发 javascript 函数,但似乎找不到解决方案。

window.onscroll = function() {myFunction()};

function myFunction() {
  if (document.body.scrollTop > 350 || document.documentElement.scrollTop > 350) {
    document.getElementById("myImg").className = "slideUp";
  }
}
.slideUp {
  animation-name: slideUp;
  -webkit-animation-name: slideUp;
  animation-duration: 1s;
  -webkit-animation-duration: 1s;
  visibility: visible;
}

@keyframes slideUp {
  0% {
    opacity: 0;
    -webkit-transform: translateY(70%);
  } 
  100% {
    opacity: 1;
    -webkit-transform: translateY(0%);
  }
}

@-webkit-keyframes slideUp {
  0% {
    opacity: 0;
    -webkit-transform: translateY(70%);
  } 
  100% {
    opacity: 1;
    -webkit-transform: translateY(0%);
  }
}

body {height:1500px;}

.col-1 {float:left}

.col-2 {float:left;padding-left:25px;}
img {width:180px;height:100px;visibility:hidden;}
hr {margin-top:400px;}
<p>Scroll down this page.</p>
<p>When you have scrolled 350px from the top, an image will slide in.</p>

<hr>
<div class="col-1">
  <img id="myImg" src="img_pulpit.jpg" width="304" height="228" alt="img">
</div> 

<div class="col-2">
  Just some text..
</div>

标签: javascripthtmlcssmobileresponsive-design

解决方案


推荐阅读