我是Javascript的新手,也是Stack Overflow的社区。我创建了一个脚本来改变特定元素的样式,结果就是这样:
HTML:
<div id="menu"></div>
<div id="cols">
<div id="cols_1"></div>
<div id="cols_2"></div>
</div>
<div id="center">
<div id="green">Green</div>
<div id="bordeaux">Bordeaux</div>
</div>
使用Javascript:
document.getElementById("green").onclick = function() {colorGreen()};
document.getElementById("bordeaux").onclick = function() {colorBordeaux()};
function colorGreen() {
document.getElementById("menu").style.borderBottom = "3px solid #448F44";
document.getElementById("cols_1").style.borderTop = "3px solid #448F44";
document.getElementById("cols_2").style.borderTop = "3px solid #448F44";
}
function colorBordeaux() {
document.getElementById("menu").style.borderBottom = "3px solid #E8920C";
document.getElementById("cols_1").style.borderTop = "3px solid #E8920C";
document.getElementById("cols_2").style.borderTop = "3px solid #E8920C";
}
JSFiddle:https://jsfiddle.net/mshy3vrh/2/
我阅读了一些关于如何在JavaScript中使用cookie的手册,但我还不知道如何使用它们。我想问一下,如果有了这个脚本,有人可以告诉我如何设置一个cookie:当有人改变颜色,点击id为绿色或波尔多的跨度时,信息被存储,如果你刷新页面,则保留所选颜色直到用户清理浏览器的缓存。 这样我就可以清楚地了解它们应该如何使用。
祝你好运, Keaire
答案 0 :(得分:0)
这个小提琴应该有用。
https://jsfiddle.net/mshy3vrh/5/
对于这个答案,我使用了Mandeep Janjua发布的this question第二个答案中的代码段
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);
}
document.getElementById("green").onclick = function() {colorGreen()};
document.getElementById("bordeaux").onclick = function() {colorBordeaux()};
var x = readCookie('color')
if (x === 'green') {
colorGreen();
} else if(x === 'bordeaux'){
colorBordeaux();
}
function colorGreen() {
document.getElementById("menu").style.borderBottom = "3px solid #448F44";
document.getElementById("cols_1").style.borderTop = "3px solid #448F44";
document.getElementById("cols_2").style.borderTop = "3px solid #448F44";
createCookie('color','green',7);
}
function colorBordeaux() {
document.getElementById("menu").style.borderBottom = "3px solid #E8920C";
document.getElementById("cols_1").style.borderTop = "3px solid #E8920C";
document.getElementById("cols_2").style.borderTop = "3px solid #E8920C";
createCookie('color','bordeaux',7);
}