问题描述
我正在尝试使用jQuery使文本从右向左滚动,但是使用垂直滚动条,您能帮我吗?当我尝试我的代码时,它可以工作,但也会使对象水平移动
var $sun = $('.sun');
var $win = $(window);
$win.on('scroll',function() {
var top = $win.scrollTop();
$sun.css("transform",`translateX(${top}px)`);
});
body {
width: 1277px;
height: 148px;
overflow-x: hidden;
}
container {
width: 600px;
height: 50px;
overflow-x: hidden;
}
.sun {
display: block;
width: 600px;
height: 50px;
margin: 75vw 0vh;
overflow-x: hidden;
}
<div id="container">
<h1 class="sun">test</h1>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
解决方法
由于您使用translateX()
,因此内容在水平移动。我假设在这个问题中,您的意思是内容正在垂直地移动,而您不希望它移动。
在这种情况下,您可以在position: fixed
元素上使用.sun
,使其相对于窗口而不是相对于文档放置,然后translateX()
逻辑将其水平移动到窗口上。页面向下滚动。试试这个:
var $sun = $('.sun');
var $win = $(window);
$win.on('scroll',function() {
var top = $win.scrollTop();
$sun.css("transform",`translateX(${top}px)`);
});
body {
width: 1277px;
height: 1148px;
overflow-x: hidden;
}
.sun {
display: block;
width: 600px;
height: 50px;
overflow-x: hidden;
position: fixed;
top: 10px;
left: 10px;
}
<div id="container">
<h1 class="sun">test</h1>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>