Javascript-форум (https://javascript.ru/forum/)
-   jQuery (https://javascript.ru/forum/jquery/)
-   -   Добавить событие mouseover (https://javascript.ru/forum/jquery/39722-dobavit-sobytie-mouseover.html)

dikucher 09.07.2013 15:05

Добавить событие mouseover
 
имеется скрипт http://web.enavu.com/tutorials/makin...uery-carousel/
Мне нужно добавить, чтобы при наведении мышки на элементы #right_scroll img ( left_scroll img ) происходила прокрутка до тех пор, пока я не уберу мышку

добавил следующий код, где событие click заменил на mouseover.
но это не решает мою задачу, прокрутка происходит единожды ( т.е. код работает так, как должен работать, он покручивает картинку на 1-у позицию, только вместо события click теперь событие mouseover)
Я вроде как понимаю, что надо добавить новую функцию ( или условие, не знаю как правильно выразиться, так как с JS на Вы и шепотом ), но как это реализовать, увы не знаю

вот наглядно где именно я заменяю событие click

$('#left_scroll img').mouseover(function(){

        var item_width = $('#carousel_ul li').outerWidth() + 10;

        /* same as for sliding right except that it's current left indent + the item width (for the sliding right it's - item_width) */
        var left_indent = parseInt($('#carousel_ul').css('left')) + item_width;

        $('#carousel_ul:not(:animated)').animate({'left' : left_indent},500,function(){

            /* when sliding to left we are moving the last item before the first list item */
            $('#carousel_ul li:first').before($('#carousel_ul li:last'));

            /* and again, when we make that change we are setting the left indent of our unordered list to the default -210px */
            $('#carousel_ul').css({'left' : '-210px'});
        });
    });

skrudjmakdak 09.07.2013 15:16

ссылочка битая получилась.. сделайте в ней пробел что ли.. чтобы распознавалась не как ссылка

dikucher 09.07.2013 15:48

Спасибо, исправил

skrudjmakdak 09.07.2013 16:13

вот там такой код. весь..
$(document).ready(function() {  
        //move the last list item before the first item. The purpose of this is if the user clicks previous he will be able to see the last item.  
        $('#carousel_ul li:first').before($('#carousel_ul li:last'));  
  
        //when user clicks the image for sliding right  
        $('#right_scroll img').click();  
  
        //when user clicks the image for sliding left  
        $('#left_scroll img').click(function(){  
  
            var item_width = $('#carousel_ul li').outerWidth() + 10;  
  
            /* same as for sliding right except that it's current left indent + the item width (for the sliding right it's - item_width) */  
            var left_indent = parseInt($('#carousel_ul').css('left')) + item_width;  
  
            $('#carousel_ul').animate({'left' : left_indent},{queue:false, duration:500},function(){  
  
            /* when sliding to left we are moving the last item before the first item */  
            $('#carousel_ul li:first').before($('#carousel_ul li:last'));  
  
            /* and again, when we make that change we are setting the left indent of our unordered list to the default -210px */  
            $('#carousel_ul').css({'left' : '-210px'});  
            });  
  
        });  
  });

и есть функция при клике.. сам клик убираем и присваиваем функции имя, получается:
var click_img = function() {  

	//get the width of the items ( i like making the jquery part dynamic, so if you change the width in the css you won't have o change it here too ) '  
	var item_width = $('#carousel_ul li').outerWidth() + 10;  

	//calculate the new left indent of the unordered list  
	var left_indent = parseInt($('#carousel_ul').css('left')) - item_width;  

	//make the sliding effect using jquery's anumate function '  
	$('#carousel_ul').animate({'left' : left_indent},{queue:false, duration:500},function(){  

		//get the first list item and put it after the last list item (that's how the infinite effects is made) '  
		$('#carousel_ul li:last').after($('#carousel_ul li:first'));  

		//and get the left indent to the default -210px  
		$('#carousel_ul').css({'left' : '-210px'});  
	});  
}


теперь эту функцию надо вызывать:
var time_img; 
$('#left_scroll img').mouseover(function(){
	time_img = setInterval(click_img, 2000);// вызывать нашу функцию каждые 2 секунды
	});

$('#left_scroll img').mouseout(function(){
	clearInterval(time_img);// убираем мышку, убираем вызов нашей функции по интервалу
	});

dikucher 09.07.2013 17:05

уже минут 40 пытаюсь разобрать, как оно должно работать, но ничего не выходит. Не составит ли вам труда показать готовой конечный код ?

skrudjmakdak 09.07.2013 17:11

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Infinite Carousel Tutorial</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
  $(document).ready(function() {
        //move he last list item before the first item. The purpose of this is if the user clicks to slide left he will be able to see the last item.
        $('#carousel_ul li:first').before($('#carousel_ul li:last')); 
        
        
        //when user clicks the image for sliding right        
		var click_img_next = function(){
        
            //get the width of the items ( i like making the jquery part dynamic, so if you change the width in the css you won't have o change it here too ) '
            var item_width = $('#carousel_ul li').outerWidth() + 10;
            
            //calculae the new left indent of the unordered list
            var left_indent = parseInt($('#carousel_ul').css('left')) - item_width;
            
            //make the sliding effect using jquery's anumate function '
            $('#carousel_ul:not(:animated)').animate({'left' : left_indent},500,function(){    
                
                //get the first list item and put it after the last list item (that's how the infinite effects is made) '
                $('#carousel_ul li:last').after($('#carousel_ul li:first')); 
                
                //and get the left indent to the default -210px
                $('#carousel_ul').css({'left' : '-210px'});
            }); 
        }
		
		var time_img; 
		$('#right_scroll img').mouseover(function(){
			time_img = setInterval(click_img_next, 2000);// вызывать нашу функцию каждые 2 секунды
		});

		$('#right_scroll img').mouseout(function(){
			clearInterval(time_img);// убираем мышку, убираем вызов нашей функции по интервалу
		});
        
        //when user clicks the image for sliding left
        $('#left_scroll img').click(function(){
            
            var item_width = $('#carousel_ul li').outerWidth() + 10;
            
            /* same as for sliding right except that it's current left indent + the item width (for the sliding right it's - item_width) */
            var left_indent = parseInt($('#carousel_ul').css('left')) + item_width;
            
            $('#carousel_ul:not(:animated)').animate({'left' : left_indent},500,function(){    
            
            /* when sliding to left we are moving the last item before the first list item */            
            $('#carousel_ul li:first').before($('#carousel_ul li:last')); 
            
            /* and again, when we make that change we are setting the left indent of our unordered list to the default -210px */
            $('#carousel_ul').css({'left' : '-210px'});
            });
            
            
        });
  });
</script>
<style type="text/css">

#carousel_inner {
float:left; /* important for inline positioning */
width:630px; /* important (this width = width of list item(including margin) * items shown */ 
overflow: hidden;  /* important (hide the items outside the div) */
/* non-important styling bellow */
background: #F0F0F0;
}

#carousel_ul {
position:relative;
left:-210px; /* important (this should be negative number of list items width(including margin) */
list-style-type: none; /* removing the default styling for unordered list items */
margin: 0px;
padding: 0px;
width:9999px; /* important */
/* non-important styling bellow */
padding-bottom:10px;
}

#carousel_ul li{
float: left; /* important for inline positioning of the list items */                                    
width:200px;  /* fixed width, important */
/* just styling bellow*/
padding:0px;
height:110px;
background: #000000;
margin-top:10px;
margin-bottom:10px; 
margin-left:5px; 
margin-right:5px; 
}

#carousel_ul li img {
.margin-bottom:-4px; /* IE is making a 4px gap bellow an image inside of an anchor (<a href...>) so this is to fix that*/
/* styling */
cursor:pointer;
cursor: hand; 
border:0px; 
}
#left_scroll, #right_scroll{
float:left; 
height:130px; 
width:15px; 
background: #C0C0C0; 
}
#left_scroll img, #right_scroll img{
/*styling*/
cursor: pointer;
cursor: hand;
}
</style>
</head>
<body>
<h1 style='color:black'>Infinite Carousel Demonstration</h1>
  <div id='carousel_container'>
  <div id='left_scroll'><img src='left.png' /></div>
    <div id='carousel_inner'>
        <ul id='carousel_ul'>
            <li><a href='#'><img src='item1.png' /></a></li>
            <li><a href='#'><img src='item2.png' /></a></li>
            <li><a href='#'><img src='item3.png' /></a></li>
            <li><a href='#'><img src='item4.png' /></a></li>
            <li><a href='#'><img src='item5.png' /></a></li>
        </ul>
    </div>
  <div id='right_scroll'><img src='right.png' /></div>
  </div>
</body>
</html>

skrudjmakdak 09.07.2013 17:12

сделал только вперед.. таким же макаром можно сделать назад
п.с. держите мышку над кнопкой более 2 секунд

dikucher 09.07.2013 17:25

да, это я увидел. Спасибо

Сделал, но мне нужно чтоб сохранилась действия клика

skrudjmakdak 09.07.2013 17:33

там 2 строчки прописать.. за вас писать не будут, учитесь сами пытаться решать))
допишите
$('#right_scroll img').click(function(){
            click_img_next();
        });

dikucher 09.07.2013 17:38

$('#right_scroll').click(function(){
click_img_next();
});


Часовой пояс GMT +3, время: 10:29.