如何使此 js 仅影响原始悬停元素的子元素,而不给出所有单独的 .g_scroll 或 .left/.right 标签 id?
function loopRight(){
$('.g_scroll').stop().animate({scrollLeft:'+=20'}, 'fast', 'linear', loopRight);
}
function loopLeft(){
$('.g_scroll').stop().animate({scrollLeft:'-=20'}, 'fast', 'linear', loopLeft);
}
function stop(){
$('.g_scroll').stop();
}
$('#right').hover(function () {
loopRight().children();
},function () {
stop();
});
$('#left').hover(function () {
loopLeft();
},function () {
stop();
});
JSfiddle(令人困惑,但必要)html结构:https://jsfiddle.net/6rbn18cL/
演示如何重命名:https://jsfiddle.net/z9u3azqy/
最佳答案
所以在这里,我“合并”了两个箭头处理程序。
然后,需要根据要滚动的宽度进行计算来确定“滚动”速度,该宽度可能并不总是元素宽度的 100%。
此脚本允许您轻松确定 100% 滚动的速度。
然后,如果已经滚动了一段距离,它会计算速度。
$(document).ready(function(){
function moveit(arrow){
// Adjust you delay here
var delay = 2000; // delay to scroll 100%
var animationDelay;
var slider = arrow.siblings(".g_scroll");
var distance = slider.width();
var scrolled = slider.scrollLeft()+1; // +1 is to avoid infinity in the math below
if(arrow.hasClass("scroller_l")){
distance = -distance;
animationDelay = -distance * (-distance/delay)*(-distance+scrolled);
}else{
animationDelay = distance * (distance/delay)*(distance-scrolled);
}
slider.stop().animate({scrollLeft:distance}, animationDelay, 'linear');
}
function stop(arrow){
arrow.siblings(".g_scroll").stop();
}
$('.scroller_l, .scroller_r').hover(function(){
moveit($(this));
},function() {
stop($(this));
});
}); // ready
--第一个答案--
首先,您不能多次使用同一个 id
。
因此,我从 HTML 中删除了 id="left"
和 id="right"
。
现在的技巧是使用 $(this)
将悬停的箭头传递给您的函数。
并找到它的兄弟元素 .g_scroll
。
$(document).ready(function(){
function loopRight(arrow){
arrow.siblings(".g_scroll").stop().animate({scrollLeft:'+=20'}, 'fast', 'linear', loopRight);
}
function loopLeft(arrow){
arrow.siblings(".g_scroll").stop().animate({scrollLeft:'-=20'}, 'fast', 'linear', loopLeft);
}
function stop(arrow){
arrow.siblings(".g_scroll").stop();
}
$('.scroller_r').hover(function(){
loopRight($(this));
},function() {
stop($(this));
});
$('.scroller_l').hover(function(){
loopLeft($(this));
},function() {
stop($(this));
});
});
关于javascript - 重新安排 js 以适应更多灵活性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44656776/