简体   繁体   English

每 X 秒更改一次文本颜色 JavaScript

[英]Change Text Color Every X Seconds JavaScript

New to javascript. javascript 的新功能。 I am writing this website and I want to randomly change the color of the logo periodically whilst the mouse hovers over it.我正在写这个网站,我想在鼠标悬停在徽标上时定期随机更改徽标的颜色。 So it goes color1, then waits x milliseconds, then color2 and so on until the mouse is not hovering over it anymore.所以它是 color1,然后等待 x 毫秒,然后是 color2,依此类推,直到鼠标不再悬停在它上面。 So far I am only able to change the logo to one randomly chosen color.到目前为止,我只能将徽标更改为一种随机选择的颜色。 Furthermore I think the way I am using 'mouseover' and 'mouseout' seems pretty confusing and inefficient, is there a better way to use them?此外,我认为我使用“mouseover”和“mouseout”的方式似乎很混乱且效率低下,有没有更好的方法来使用它们?

My code (I've left only the essentials)我的代码(我只留下了必需品)

!DOCTYPE html>

<html lang="en">
    <head>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
        <link href="styles.css" rel="stylesheet">
        <title>My Webpage</title>
        <script>
            document.addEventListener('DOMContentLoaded', function listen() {
                var logo = document.querySelector('.logo-btn');
                logo.addEventListener("mouseover", event => setTimeout(changeColor(event), 500));
                logo.addEventListener("mouseout", event => resetColor(event));
            })

            function changeColor (event) {
                var colors = ["#ff3300", "#fbfb32", "#99ff33", "orange", "magenta", "#3399ff"]
                var color = colors[Math.floor(Math.random() * colors.length)];
                var logo = event.target;

                logo.style.color = color;
            }
            function resetColor (event) {
                var logo = event.target;
                logo.style.color = "black";
            }
        </script>
    </head>
    <body>
        <header>
            <div class="header-logo">
                <a href="x">
                    <button class="logo-btn">Logo</button>
                </a>
            </div>
    </body>
</html>

header {
    background-color: #fff;
    height: 80px;
    position: relative;
}

.header-logo {
    font-size: 50px;
    position: absolute;
    bottom: -15px;
    left: 40px;
}

.logo-btn {
    background-color: transparent;
    border: none;
    text-align: bottom;
}
```
Thank you very much!

You had done it pretty much right.你做得非常正确。 All you needed was to use setInterval instead of setTimeout .您所需要的只是使用setInterval而不是setTimeout Also, you need to store the interval in a variable and clear it on mouseout so that the text does not keep changing the color.此外,您需要将间隔存储在变量中并在mouseout时将其清除,以便文本不会不断改变颜色。

 let interval; document.addEventListener('DOMContentLoaded', function listen() { var logo = document.querySelector('.logo-btn'); logo.addEventListener("mouseover", event => {interval = setInterval(()=>changeColor(event), 500)}); logo.addEventListener("mouseout", event => resetColor(event)); }) function changeColor(event) { var colors = ["#ff3300", "#fbfb32", "#99ff33", "orange", "magenta", "#3399ff"] var color = colors[Math.floor(Math.random() * colors.length)]; var logo = event.target; logo.style.color = color; } function resetColor(event) { var logo = event.target; logo.style.color = "black"; clearInterval(interval); }
 header { background-color: #fff; height: 80px; position: relative; }.header-logo { font-size: 50px; position: absolute; bottom: -15px; left: 40px; }.logo-btn { background-color: transparent; border: none; text-align: bottom; }
 <:DOCTYPE html> <html lang="en"> <head> <link href="https.//cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min:css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <script src="https.//cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script> <link href="styles.css" rel="stylesheet"> <title>My Webpage</title> </head> <body> <header> <div class="header-logo"> <a href="x"> <button class="logo-btn">Logo</button> </a> </div> </header> </body> </html>

It should be like this...应该是这样的……

let colors = [1,2,3],
element = document.qureySelector('whatever-your-logo'),
colorIndex = 0;
function changeColor(){
    //set color
    element.style.color = colors[colorIndex];
    //change to next color
    colorIndex++;
   // if it's last color then back to first colorIndex
   if(colorIndex >= colors.length-1) colorIndex = 0;
}


//Interval
let priod = 1000; //in ms
let interval = setInterval(changeColor, priod);


//done...

A recursive function can be a solution for your problem.递归 function 可以解决您的问题。

You set mouseOver variable on 1 when mouse is over, and on 0 when mouse is out.鼠标悬停时将 mouseOver 变量设置为 1,鼠标移出时设置为 0。 You also call setColor on mouseover and check if mouse is over with mouseOver flag.您还可以在 mouseover 上调用 setColor 并使用 mouseOver 标志检查鼠标是否结束。

Now you call setColor that set a new color every time it's called based on selected variable现在您调用 setColor 来设置每次基于所选变量调用的新颜色

var logo = document.querySelector('.logo-btn');

logo.addEventListener("mouseover", event => {setColor(event); mouseOver = 1});
logo.addEventListener("mouseout", event => resetColor(event));

var colors = ["#ff3300", "#fbfb32", "#99ff33", "orange", "magenta", "#3399ff"],
    selected = 0,
    mouseOver = 0

function setColor(e){
    e.target.style.backgroundColor = colors[selected]

    if(mouseOver){
        setTimeout(function(){
            if(colors.length > selected + 1){
                selected = 0
            }
            else{
                selected ++
            }
            setColor(e)           
        }, 500)
    }
}

function resetColor(event){
    selected = 0
    mouseOver = 0
    e.target.style.backgroundColor = colors[selected]
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM