简体   繁体   English

单击按钮时setInterval + image src更改

[英]setInterval + image src changes when clicked on button

I want to give blink effect(dark and light) when clicked on the button.I have written the following code but it does not work.So please help me. 我想在单击按钮时产生闪烁效果(暗和亮)。我编写了以下代码,但是它不起作用。请帮助我。

$(document).ready(function () {

    $(".search").click(function () {
        setInterval(function () {
            var curSrc = $("#red").attr('src');

            if (curSrc === '../images/lightred.jpg') {
                $(curSrc).attr("src", "../images/Darkred.jpg");
            }
            if (curSrc === '../images/Darkred.jpg') {
                $(curSrc).attr("src", "../images/lightred.jpg");
            }
        }, 2000);
    });

});

curSrc is your source attribute, yet you are trying to wrap it in jQuery, that won't make it an object. curSrc是您的源属性,但是您尝试将其包装在jQuery中,但这不会使其成为对象。 You'll have to target #red again and then set the source: 您必须再次定位#red ,然后设置源:

if (curSrc === '../images/lightred.jpg') {
            $("#red").attr("src", "../images/Darkred.jpg");
}
if (curSrc === '../images/Darkred.jpg') {
            $("#red").attr("src", "../images/lightred.jpg");
}

It seems the question might be how to make the button blink. 看来问题可能出在如何使按钮闪烁。 This can be done with the css background-color property. 这可以通过使用CSS的background-color属性来完成。 CSS is a better fit, assuming lightRed and darkRed are solid colors. 假设lightRed和darkRed是纯色,则CSS更合适。 If the images are required you can use the background-image property. 如果需要图像,则可以使用background-image属性。

<input type="button" class="search lightRed" value="Search"/>
<style>
    .lightRed { background-color: lightcoral }
    .darkRed { background-color: darkRed }
</style>
<script>
    $(document).ready(function(){
        $(".search").click(function(){
            setInterval(function(){
                var isLightRed = $(".search").hasClass("lightRed");
                if (isLightRed) {
                    $(".search").removeClass("lightRed").addClass("darkRed");
                } else {
                    $(".search").removeClass("darkRed").addClass("lightRed");
                }
            },2000);
        });
    });
</script>

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

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