描述:
button页面选择颜色按钮,另一界面div变色
效果:
实现:
点击button:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<button>red</button>
<button>green</button>
<button>blue</button>
<script>
var bns=document.getElementsByTagName("button");
for(var i=0;i<bns.length;i++){
bns[i].addEventListener("click",clickHandler)
}
function clickHandler(e) {
localStorage.color=this.textContent;
}
</script>
</body>
</html>
接受信息 div变色:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
div
{
width: 100px;
height: 100px;
background-color: red;
border-radius: 50px;
}
</style>
</head>
<body>
<div></div>
<script>
var div=document.querySelector("div");
window.addEventListener("storage",storageHandler);
function storageHandler(e) {
if(e.key==="color"){
div.style.backgroundColor=e.newValue;//将每次的新数据 赋予div的color
}
}
</script>
</body>
</html>