簡體   English   中英

Mouseenter,保留在epmty DIV中。 更改顏色並將其刪除

[英]Mouseenter, mouseleave in epmty DIV. Change a color and remove it

我在css和js的html中有這個簡單的代碼...但是它沒有運行。 我是JS的初學者,我無法找出為什么我的mouseover(甚至嘗試過mouseenter)不起作用。 有人可以向我解釋嗎? 我也需要做鼠標離開,所以當用戶離開盒子時,紅色消失了。 我知道,這很簡單,但我無法解決:(

謝謝

 div { width: 300px; height: 300px; border: 1px solid black; } 
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <div></div> <script> var box = document.querySelector('div')[0]; if (box) { box.addEventListener('mouseover', colorin); } function colorin(e) { e.style.backgroundColor = "red"; } </script> </body> </html> 

我在下面附加了工作代碼,您需要更改e.style.backgroundColor = "red"; e.target.style.backgroundColor = "red"; 沒有.target,就沒有DOM元素可以更改。 另外,正如您提到的,您需要有一個mouseout事件,當用戶不再專注於該div時,它將顏色恢復為白色。

<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
        <style>

        div {
            width: 300px;
            height: 300px;
            border: 1px solid black;
        }
        </style>
    </head>
    <body>
        <div></div>

        <script>
            var box = document.querySelector('div');
            if(box) {
                box.addEventListener('mouseenter', colorin);
                box.addEventListener('mouseout', colorout);

            }

            function colorin(e) {
                e.target.style.backgroundColor = "red";
            }

            function colorout(e) {
                e.target.style.backgroundColor = "white";
            }
        </script>
    </body>
    </html>

暫無
暫無

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

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