我需要在单击按钮时更改内容的字体大小并将其存储在cookie中,该代码首次可用于页面加载,但是我在网站上具有无限滚动功能,因此无法获得下一页Cookie的值和字体大小显示为默认值。
我尝试将所有代码全部放在(document)on('ready',function)或window.on(load)
var Cookie = "fontsize";
$(document).ready(function () {
var fontsize = $.cookie(Cookie) || 'normal';
if (fontsize == "normal") {
$(".td-post-content p").css({
"font-size": "20px"
});
console.log(fontsize + "normal state")
}
else {
$( '.td-post-content p' ).css( 'font-size', $.cookie("fontsize") + "px");
console.log(fontsize + "else state")
};
});
function getSize() {
if (Cookie){
size = $( '.td-post-content p' ).css( 'font-size', $.cookie("fontsize") + "px");
size = parseInt(size, 10);
}
size = $('.td-post-content p').css( "font-size");
size = parseInt(size, 10);
}
getSize()
console.log(size + "after getsize")
$('#contentsWrapper').on( "click", "#up", function() {
if ((size + 1) <= 26) {
$( ".td-post-content p" ).css( "font-size", "+=1" );
$( "#font-size" ).text( size += 1 );
}
$.cookie(Cookie, fontsize = size, {expires: 365, path: '/', domain : ''});
console.log(size);
});
$('#contentsWrapper').on( "click", "#down", function() {
if ((size - 1) >= 16) {
$( ".td-post-content p" ).css( "font-size", "-=1" );
$( "#font-size" ).text( size -= 1 );
}
$.cookie(Cookie, fontsize = size, {expires: 365, path: '/', domain : ''});
console.log(size);
});
答案 0 :(得分:0)
Here is an example of using a cookie value to update a style tag。
本质上,在页面加载时,您将检索cookie值并创建一个标记,以通过CSS规则定位您的页面内容。这样,它仍然适用于以后加载的项目。
单击按钮时,需要更新cookie,然后刷新样式标签。
JS
var cookie = "fontsize";
var getFontSize = function(){
var value = parseInt($.cookie(cookie))
return value||20;
}
var changeFontSize = function(direction){
var newSize = Math.min(25, Math.max(15, getFontSize()+direction))
$.cookie(cookie, newSize, {expires: 365, path: '/', domain : ''});
updateFontSize(newSize)
}
var updateFontSize = function(fontsize){
var style = $('#font_size_style')
if(!style.length){
style = $('<style id="font_size_style">')
$(document.body).append(style)
}
style.text(".td-post-content p { font-size: "+fontsize+"px; }")
$( "#font-size" ).text(fontsize);
}
var initFontSize = function(){
var fontsize = getFontSize()
console.log(fontsize)
updateFontSize(fontsize)
}
$(document).ready(initFontSize);
$('#contentsWrapper').on( "click", "#up", function() {
changeFontSize(1)
});
$('#contentsWrapper').on( "click", "#down", function() {
changeFontSize(-1)
});
$("#add").on( "click",function() {
var paragraphs = $(".td-post-content p")
$(".td-post-content").append($("<p>Test paragraph "+(paragraphs.length+1)+"</p>"))
});
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.js"></script>
<div id="contentsWrapper">
<button id="up">^</button>
<div id="font-size" style="display: inline-block; width: 30px;"></div>
<button id="down">v</button>
<div class="td-post-content">
<p>
Test paragraph 1
</p>
</div>
</div>
<button id="add">Add Paragraph
</button>
</button>