我正在尝试将一个cookie添加到jquery滑块,它工作正常,直到我刷新页面并在滑块中向后移动(当添加cookie中的值(valuevalue)而不是添加(value + value)
错误发生在slideMargin + = width(如果没有涉及到cookie,则可以正常工作),如果我将其更改为slideMargin - = width它工作正常但是走错路。
代码:
jQuery(document).ready(function($) {
$(function () {
var $slider = $('#slider');
var $slideContainer = $('.slides', $slider);
var $slides = $('.slide', $slider);
var slideMargin = readCookie('slide');
var width = 770;
var slidesLength = ($slides.length-2)*770;
document.onload = checkCookie();
$('#next-gal')
.on('click', nextGal);
$('#prev-gal')
.on('click', prevGal);
function nextGal() {
slideMargin -= width;
createCookie('slide', slideMargin,1);
$slideContainer.animate({'margin-left':(slideMargin)},1000,function() {
if (slideMargin === (-Math.abs(($slides.length-1)*770))) {
slideMargin = -Math.abs(width);
$slideContainer.css('margin-left', -width);
}
});
}
function prevGal() {
slideMargin += width;
createCookie('slide', slideMargin,1);
$slideContainer.animate({'margin-left':(slideMargin)},1000,function() {
if (slideMargin === 0) {
slideMargin = -Math.abs(slidesLength);
$slideContainer.css('margin-left', -Math.abs(slidesLength));
}
});
}
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
function checkCookie() {
if (slideMargin != null) {
$slideContainer.css('margin-left', -Math.abs(slideMargin));
createCookie('slide', slideMargin,1);
}
else {
createCookie( 'slide', -1540 ,1);
slideMargin = -770;
$slideContainer.css('margin-left', -Math.abs(slideMargin));
}
}
});
});
任何帮助都会很高兴收到。
拉斯
答案 0 :(得分:0)
您从网页的Cookie中读取的值将是一个字符串。我怀疑你需要在开始在方程式中使用它之前将其强制转换为数字 - 否则你会得到时髦的东西......
我替换了这个:
var slideMargin = readCookie('slide');
与
var slideMargin = parseInt(readCookie('slide')) || 0; // if no cookie value, or if it's not a number, default to zero
希望这有帮助!