簡體   English   中英

如何通過單擊第 1 頁中的按鈕更改第 2 頁中 html 的顏色

[英]How to change color of html in page 2 by clicking the button in page 1

**page1.html**

     <button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
  document.querySelector(".example").style.backgroundColor = "red";
}
</script>
**page2.html**

<h2 class="example">A heading with class="example"</h2>

單擊第 1 頁中的按鈕后,帶有 class 示例的 h2 標簽的背景顏色不會改變。

一種可能的解決方案是使用在同一域上的頁面上持久存儲的本地存儲。 然后在目標頁面中讀取“onload”中的值。

在第 1 頁上:

function myFunction() {
    localStorage.setItem("exampleBGColor", "red");
}

在第2頁上:

window.onload = function() {
    let BGcolor = localStorage.getItem("exampleBGColor");
    if(BGcolor) {
        document.querySelector(".example").style.backgroundColor = BGcolor;
        localStorage.removeItem("exampleBGColor");
    }
}

希望這可以幫到你。

要在另一個頁面中進行更改,無法直接從您的頁面訪問它。

所以你可以通過一些創新的方式來做到這一點!

例如:

  • 您可以將參數傳遞到 url 中的另一個頁面(“page2”),然后在“page2”中從查詢參數中讀取它並設置元素的顏色。

  • 您可以在本地存儲中設置顏色,然后在新頁面中從本地存儲中讀取它並設置元素的顏色。

您可以使用 LocalStorage api 實現類似的行為。

第一頁:

<html>
<head>
    <meta charset='utf-8'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <title>Local Storage</title>
    <meta name='viewport' content='width=device-width, initial-scale=1'>
    <script>
        function setColor() {
            localStorage.setItem('currentColor', 'red');
        }
    </script>
</head>
<body>
    <button onclick="setColor()">
        Change Color
    </button>
</body>
</html>

第二頁:

<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <title>Local Storage</title>
    <meta name='viewport' content='width=device-width, initial-scale=1'>
    <script>
        window.addEventListener('storage', function(e) {
            const div = document.getElementById('div');
            div.style.backgroundColor = e.key === 'currentColor' ? e.newValue : null;
        });
    </script>
</head>
<body>
    <div id="div">
        My Color Will Change
    </div>
</body>
</html>

使用storage事件偵聽器允許頁面 2 中的 div 響應式更新其顏色。 您可以在此處了解有關 LocalStorage 的更多信息。

正如@juanram0n、Ilia @Afzali 和@dev_junwen 所說,您可以使用 JavaScript Window localStorage 屬性來實現。

*page1.html*

<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
 // Store backgroundColor
 localStorage.setItem("bgColor", "red");
}
</script>


*page2.html*

<h2 class="example">A heading with class="example"</h2>
<script>
document.querySelector(".example").style.backgroundColor = localStorage.getItem("bgColor");
</script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM