Запись в cookie значения id
Есть два скрипта и кнопка которые меняют фон в заданном месте <div id="col">ТЕКСТ</div>
/* МЕНЯЕТ ФОН СТАТЬИ ПРИ НАЖАТИИ НА КНОПКУ */
window.onload = function() {
document.getElementById('SuperButton').onclick = function()
{
if(document.getElementById('col').className != 'whitefon')
{
document.getElementById('col').className = 'whitefon';
}
else
{
document.getElementById('col').className = 'topic-content';
}
}
}
/* КНОПКА МЕНЯЮЩАЯ ФОН И САМУ СЕБЯ */
$(function(){
$('.button1, .button2').click(function(){
$('.button1, .button2').toggleClass('active');
});
});
И сама кнопка, которая не только меняет фон в id=col, но и меняет текст и цвет при нажатии. <div id="SuperButton" class="exemple"> <span class="button1 active">сделать белый фон</span> <span class="button2">сделать тёмный фон</span> </div> Код:
.exemple { |
Цитата:
https://learn.javascript.ru/cookie Там даже даны примеры функций для более простой работы с куками. ;) Цитата:
Можно записать "пусто". Или записать некое значение на ооочень короткий интервал хранения и по истечении этого времени кука "умрет"... В статейке выше есть пример функции deleteCookie()... |
Цитата:
|
Если зменять на пустое значение, то при повторном нажатии просто удалит класс whitefon? А какую часть кода записывать?
|
Цитата:
Цитата:
|
Не очень короткий, а меньше, зачем жизнь продлевать зря )
|
laimas, я так же писал
Цитата:
|
Цитата:
|
Я по примерм и пробовал, но у меня перестаёт работать скрипт вообще.
|
Цитата:
|
function getCookie(name) {
var matches = document.cookie.match(new RegExp(
"(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
));
return matches ? decodeURIComponent(matches[1]) : undefined;
}
$(function(){
var yourcolor = getCookie('color');
if(yourcolor){
if(yourcolor=="button1"){
} else if(yourcolor=="button2"){
$('.button1').removeClass('active');
$('.button2').addClass('active');
}
}
$('.button1, .button2').click(function(){
$('.button1, .button2').toggleClass('active');
if($('.button1').hasClass('active')){
var date = new Date(new Date().getTime() + 60 * 1000);
document.cookie = "color=button1; path=/; expires=" + date.toUTCString();
} else if($('.button2').hasClass('active')){
var date = new Date(new Date().getTime() + 60 * 1000);
document.cookie = "color=button2; path=/; expires=" + date.toUTCString();
}
});
});
Вот, но не работает. |
window.onload = function() {
document.getElementById('SuperButton').onclick = function()
{
if(document.getElementById('col').className != 'whitefon')
{
document.getElementById('col').className = 'whitefon';
}
else
{
document.getElementById('col').className = 'topic-content';
}
}
}
function getCookie(name) {
var matches = document.cookie.match(new RegExp(
"(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
));
return matches ? decodeURIComponent(matches[1]) : undefined;
}
$(function(){
var yourcolor = getCookie('color');
// alert(1);
if(yourcolor){
if(yourcolor=="button1"){
} else if(yourcolor=="button2"){
$('.button1').removeClass('active');
$('.button2').addClass('active');
}
}
$('.button1, .button2').click(function(){
$('.button1, .button2').toggleClass('active');
if($('.button1').hasClass('active')){
var date = new Date(new Date().getTime() + 60 * 1000);
document.cookie = "color=button1; path=/; expires=" + date.toUTCString();
} else if($('.button2').hasClass('active')){
var date = new Date(new Date().getTime() + 60 * 1000);
document.cookie = "color=button2; path=/; expires=" + date.toUTCString();
}
});
});
Точнее записывает фон кнопки, а фон самого текста .whitefon нет. |
Цитата:
|
http://codepen.io/warycooper/pen/yVpxNL - Вот здесь полный пример
|
Цитата:
Если я правильно понял, нужно мочь кнопками менять фон и при перезагрузке последний фон должен оставаться? |
Цитата:
|
Цитата:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv='Content-Type' content='text/html; charset=windows-1251' />
<script src='http://code.jquery.com/jquery-latest.js'></script>
<!--
<script src="https://code.angularjs.org/1.3.9/angular.min.js"></script>
<script src="https://code.angularjs.org/1.3.9/angular-route.js"></script>
-->
<style type='text/css'>
</style>
<script type='text/javascript'>
$(function(){
var clr=getCookie('color');
if (clr) {
$('#test').css('background-color',clr);
};
$('#btn1').click(function(){
var clr='#ffffff';
$('#test').css('background-color',clr);
setCookie('color',clr);
});
$('#btn2').click(function(){
var clr='red';
$('#test').css('background-color',clr);
setCookie('color',clr);
});
});
function getCookie(name) {
var matches = document.cookie.match(new RegExp(
"(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
));
return matches ? decodeURIComponent(matches[1]) : undefined;
};
function setCookie(name, value, options) {
options = options || {};
var expires = options.expires;
if (typeof expires == "number" && expires) {
var d = new Date();
d.setTime(d.getTime() + expires * 1000);
expires = options.expires = d;
};
if (expires && expires.toUTCString) {
options.expires = expires.toUTCString();
};
value = encodeURIComponent(value);
var updatedCookie = name + "=" + value;
for (var propName in options) {
updatedCookie += "; " + propName;
var propValue = options[propName];
if (propValue !== true) {
updatedCookie += "=" + propValue;
}
};
document.cookie = updatedCookie;
}
</script>
</head>
<body>
<div>
<button id="btn1">сделать белый фон</button>
<button id="btn2">сделать тёмный фон</button>
</div>
<div id="test">Здесь меняет фон текста</div>
</body>
</html>
|
Спасибо за помощь! А как записать, что бы цвет текста тоже менялся?
|
Цитата:
|
Для работы с куками есть замечательный плагин jquey.cookie
В нем есть и полное удаление установленных кук Описание и плагин: https://github.com/carhartl/jquery-cookie |
| Часовой пояс GMT +3, время: 19:38. |