我正在尝试更改此预制代码,以便它适用于我的网站创意。我想知道如何只有当用户将鼠标悬停在其中一个li
项上时才会触发'暂停'功能;否则,旋转木马将永远循环。
如何实现这一目标?我用Google搜索并尝试了以下内容:
if ($('#element:hover').length != 0) {
pause();
}
但这不符合代码。我可以得到一些帮助吗?谢谢。
https://jsfiddle.net/lovromar/Z4VpZ/
HTML
<div id="carousel-container">
<div id="carousel-inner">
<ul id="carousel-ul">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
<li>10</li>
</ul>
</div>
</div>
CSS
#carousel-container {
width: 680px;
margin: 2em auto;
position: relative;
border: 1px solid #ccc;
overflow: hidden;
height: 250px;
}
#carousel-inner {
width: 680px;
float: left;
position: relative;
overflow: hidden;
}
#carousel-ul {
position:relative;
left:-160px;
list-style-type: none;
margin: 0px;
padding: 0px;
width:9999px;
padding-bottom:50px;
}
#carousel-ul li{
float: left;
width: 150px;
padding:0px;
height:186px;
margin: 50px 15px 0 15px;
position: relative;
background: #c0c0c0;
line-height: 186px;
font-size: 2em;
text-align: center;
}
JS
var Carousel = new
function() {
var wrapper = document.getElementById('carousel-container'),
timer = null;
var start = function() {
doCarousel();
};
var sliding = function() {
var item_width = $('#carousel-ul li').outerWidth() + 10;
var left_indent = parseInt($('#carousel-ul').css('left')) - item_width;
$('#carousel-ul:not(:animated)').animate({
'left': left_indent
}, 2000, 'linear', function() {
$('#carousel-ul li:last').after($('#carousel-ul li:first'));
$('#carousel-ul').css({
'left': '-160px'
});
});
};
var doCarousel = function() {
timer = setInterval(sliding, 2000);
};
var pause = function() {
clearInterval(timer);
timer = null;
};
var resume = function() {
doCarousel();
};
this.init = function() {
start();
};
}();
$(function() {
Carousel.init();
});
答案 0 :(得分:1)
$("#carousel-ul li").mouseover(function(){ Carousel.pause();});
答案 1 :(得分:1)
我做到了。
我改变了你声明对象的方式,它的工作原理如下:
var Carousel = {
timer :null,
wrapper: null,
init : function()
{
var self = this;
this.timer = setInterval(function(){self.sliding();}, 2000);
},
sliding : function() {
var item_width = $('#carousel-ul li').outerWidth() + 10;
var left_indent = parseInt($('#carousel-ul').css('left')) - item_width;
$('#carousel-ul:not(:animated)').animate({
'left': left_indent
}, 2000, 'linear', function() {
$('#carousel-ul li:last').after($('#carousel-ul li:first'));
$('#carousel-ul').css({
'left': '-160px'
});
})},
pause : function() {
clearInterval(this.timer);
this.timer = null;
},
resume : function() {
this.init();
},
};
$(function() {
alert("init");
Carousel.init();
$('#carousel-ul li').mouseover(function(){
//clearInterval(timer);
//timer = null;
//pause();
Carousel.pause();
});
$('#carousel-ul li').mouseout(function(){
//clearInterval(timer);
//timer = null;
//pause();
Carousel.resume();
});
});
这是你的Jsfiddle:https://jsfiddle.net/Z4VpZ/4/
通常,我避免使用Javascript函数来声明类,我使用js对象{}
,或者使用ECMASCRIPT 6 class statement。