[英]Slide in div on scroll with fixed height
大家 我有问题,希望有人能帮助我。 我有这个项目,当用户向下滚动并向上滚动以向右移动时,需要将红色div向左移动(您可以看到下面的代码)。 关键是该站点是固定高度,并且不能具有滚动条。 JS必须检测滚动而不是页面高度。 我尝试了所有可能发现的问题,并花了将近一个星期的时间解决此问题,如果它可以做出响应,那还不错,如果还可以。
这是------> jsfiddle或Codepen的链接,我只是放置了一个按钮,以便您可以看到希望达到的效果。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<title>Document</title>
</head>
<style>
body{
overflow: hidden;
margin: 0;
padding: 0;
}
#blue{
background: blue;
width: 100%;
height:50vh;
position: absolute;
bottom: 0;
}
.red{
background: red;
width: 2000px;
height: 500px;
position: absolute;
/* position to be changed to 1000px */
left: 2000px;
transition: 2s ease-in-out;
}
</style>
<body>
<button onclick="slide()">press</button>
<div id="move" class="red">red</div>
<div id="blue">blue</div>
<script>
function slide(){
let moveRed = document.getElementById('move');
if(moveRed.style.left=='2000px'){
moveRed.style.left = '500px';
}else{
moveRed.style.left = '2000px';
}
}
</script>
</html>
谢谢,祝你白天或晚上都愉快:)
您可以创建一个单独的函数来处理滚动事件,并使用window.onwheel()
方法跟踪鼠标在页面上的滚动。
我加了|| moveRed.style.left == ''
|| moveRed.style.left == ''
到您的if语句:
if(moveRed.style.left=='2000px' || moveRed.style.left == '')
因为<div id="move">
.style.left
开头具有空值。
注意:我还为其他一些浏览器添加了CSS过渡支持。
这是代码:(运行底部的代码段进行测试)
window.onwheel = wheelslide; // window scroll function function wheelslide(e) { var moveRed = document.getElementById('move'); // scrolling downward if(e.deltaY > 0) { if(moveRed.style.left == '2000px' || moveRed.style.left == '') moveRed.style.left = '500px'; } else { if(moveRed.style.left == '500px') moveRed.style.left = '2000px'; } } // button function function slide() { let moveRed = document.getElementById('move'); if(moveRed.style.left=='2000px' || moveRed.style.left == '') { moveRed.style.left = '500px'; } else { moveRed.style.left = '2000px'; } }
body{ overflow: hidden; margin: 0; padding: 0; } #blue{ background: blue; width: 100%; height:50vh; position: absolute; bottom: 0; } .red{ background: red; width: 2000px; height: 500px; position: absolute; left: 2000px; transition: 2s ease-in-out; -moz-transition: 2s ease-in-out; -webkit-transition: 2s ease-in-out; }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"> </script> <title>Document</title> </head> <body> <button onclick="slide()">press</button> <div id="move" class="red">red</div> <div id="blue">blue</div> </body> </html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.