Failed to set left using CSS + jQuery

I am trying to implement a carousel with jQuery based on http://www.queness.com/post/923/create-a-simple-infinite-carousel-with-jquery . It all works fine. Only when I sit down left and right do I not return to my original position. From debugging, I found out that the left set is not installed in my ul element. Code:

Javascript

var container = $('#calendarContainer ul'); var moveWidth = container[0].clientWidth / 3; var currentIndent = container.position().left; if (event.type == "swipeleft") { $('#calendarContainer ul').css('left', currentIndent - moveWidth); } if (event.type == "swiperight") { $('#calendarContainer ul').css('left', currentIndent + moveWidth); } 

Html

 <div id="calendarContainer" > <ul> <li id ="calendarDivLeft"> <fieldset id="calendarWeekGridLeft" class="ui-grid-a"></fieldset> </li> <li id ="calendarDiv" > <fieldset id="calendarWeekGrid" class="ui-grid-a"></fieldset> </li> <li id="calendarDivRight"> <fieldset id="calendarWeekGridRight" class="ui-grid-a"></fieldset> </li> </ul> </div> 

CSS

 #calendarContainer ul { width : 300%; list-style: none; padding:0px; left : 0%; position:relative; margin: 0px; padding: 0px; } #calendarContainer ul li { width: 33.333%; float:left; position:relative; margin: 0px; padding: 0px; } 

For example, if the current left value is 5, and I move left at 594px, I expect it to stay to the left of -589. Instead, I get to the left of 585! If I switch to 595, the left becomes 605 instead of 600.

How is this possible?

+4
source share
2 answers

Try the following:

 $('#calendarContainer ul').css('left', function(index, oldValue){ var newValue = oldValue - moveWidth; return newValue; }); 

The css() function can take a function whose argument is the index of the element in the set and the current value of the property that was mentioned. It is just a math question in this function and returning a new value.

+4
source

CSS likes to have units. Try to specify px

 $('#calendarContainer ul').css('left', (currentIndent - moveWidth) + 'px'); 
0
source

Source: https://habr.com/ru/post/1388439/


All Articles