根据 Cookie 的存在突出显示按钮

Highlight a button based on existence of a cookie

本文关键字:显示 按钮 存在 Cookie 根据      更新时间:2023-09-26

我的网站上有几个按钮以及几个cookie。我有一个名为"chosenValue"的cookie,我想突出显示与cookie中存储的值对应的值。例如,我检索存储在 cookie 中的值:

var value = readCookie('chosenValue');

假设存储的值是"id1"。然后,我想突出显示与"id1"关联的按钮。

<input type="button" class="buttons" name="button-terms" value="id1"></input>
<input type="button" class="buttons" name="button-terms" value="id2"></input>
<input type="button" class="buttons" name="button-terms" value="id3"></input></h3>

目前,按钮基于悬停突出显示。但我希望它根据存储在 cookie 中的值突出显示。

/*Button stylings */
.buttons {
    border: solid;
    padding-right: 20px;
    padding-left: 20px;
    margin-right: 10px;
    margin-left: 10px
    font-size: 120%;
    background: transparent;
    margin-top: 20px;
    color: black;
    border-color: black;
    font-size: 20px;
    font-family: "brandon-grotesque",sans-serif;
}
.buttons:hover {
    background: darkred;
    border-color: black;
    color: white;
    cursor: pointer;
}

我该怎么做?

在 CSS 中将 ".buttons

:hover" 更改为 ".buttons:hover, .button-active",然后在 JavaScript 中

$(".buttons[value="+readCookie('chosenValue')+"]").addClass("button-active");

尝试:

.JS:

document.getElementById(readCookie('chosenValue')).className = 'buttons highlighted';

.CSS:

.buttons.highlighted { background: orange }