【发布时间】:2020-07-02 19:20:28
【问题描述】:
问题是我不知道如何使用 LocalStorage 来保存为按钮选择的背景颜色。我以前从未使用过 LocalStorage,但我对代码的想法是以某种方式使用 myFunction(color),它利用了 onclick 函数中的颜色值。任何帮助将不胜感激!
$("[data-toggle=popover]").popover
({
html: true,
sanitize: false,
trigger: 'focus',
content: function()
{
return $('#popover-content').html();
}
});
let targetBtn;
document.querySelectorAll('.myBtn').forEach((item) =>
{
item.addEventListener('click', (e) =>
{
targetBtn = e.target;
})
})
function myFunction(color)
{
if (targetBtn)
{
targetBtn.style.background = color;
/* Here I somehow want to use localStorage
to save the picked colors for the buttons
localStorage.setItem('targetBtn', color); */
}
}
.popover-content
{
display: flex;
justify-content: space-around;
align-items:center;
background: #efefef;
width: 230px;
height: 80px;
}
.close
{
color: #aaaaaa;
float: right;
font-size: 28px;
font-weight: bold;
position: absolute;
top:0px;
left:210px;
}
.close:hover,
.close:focus
{
color: #000;
text-decoration: none;
cursor: pointer;
transition: 0.5s;
}
.myBtn
{
background-color: #DCDCDC;
border: 0.5px solid #808080;
color: white;
width: 30px;
height: 30px;
border-radius: 6%;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
}
.demo1
{
background-color: red;
border: none;
color: white;
width: 60px;
height: 60px;
border-radius: 50%;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
}
.demo2
{
background-color: green;
border: none;
color: white;
width: 60px;
height: 60px;
border-radius: 50%;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
}
.demo3
{
background-color: blue;
border: none;
color: white;
width: 60px;
height: 60px;
border-radius: 50%;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
}
.hide
{
display: none;
}
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<button class="myBtn myBtnCorners1" data-toggle="popover" data-placement="bottom" data-html="true">1</button>
<button class="myBtn" data-toggle="popover" data-placement="bottom" data-html="true">2</button>
<div id="popover-content" class="hide">
<button class="demo1" onclick="myFunction('red')">Red</button>
<button class="demo2" onclick="myFunction('green')">Green</button>
<button class="demo3" onclick="myFunction('blue')">Blue</button>
<span class="close">×</span>
</div>
</body>
【问题讨论】:
-
欢迎来到 Stack Overflow。你的很多代码似乎没有意义。你都尝试了些什么?请提供一个最小的、可重复的示例:stackoverflow.com/help/minimal-reproducible-example
标签: javascript jquery html css local-storage