简体   繁体   English

为什么这个 jQuery 代码只工作一次?

[英]Why does this jQuery code works only once?

I have this short jQuery code to make the picture disappear when the window is resized.我有这个简短的 jQuery 代码可以在调整窗口大小时使图片消失。 For some reason, after it disappears, it doesn't appear again.由于某种原因,它消失后,就不会再出现。 Here is the code:这是代码:

$(document).ready(function(){
    $(window).resize(function(){

        if($(window).width() < 700) {
            $("#side-pic").css("display","none");


        } else if($(window).width() >= 700){

            $("#side-pic").css("display","show");
        }

    });
    });

Also if by any chance you know if there is a way to make picture move under a certain div in my code, I'll be glad to hear it!此外,如果您有机会知道是否有办法让我的代码中的某个 div 下的图片移动,我会很高兴听到它! Thank you guys in advance!提前谢谢你们!

There is no display property such as display: show .没有显示属性,例如display: show Try using $("#side-pic").css("display","block");尝试使用$("#side-pic").css("display","block"); instead.反而。

Another Alternative would be hide/show:另一种选择是隐藏/显示:

$(document).ready(function(){
    $(window).resize(function(){

        if($(window).width() < 700) {
             $("#side-pic").hide();
        } 
        else if($(window).width() >= 700) {
             $("#side-pic").show();
        }

    });
});

That's because the "show" is not a valid display value.那是因为"show"不是有效的display值。 https://developer.mozilla.org/en-US/docs/Web/CSS/display https://developer.mozilla.org/en-US/docs/Web/CSS/display

Also, why the else if , isn't an else good enough?另外,为什么else if else不够好?
Or rather a reusable CSS class and jQuery's toggleClass() Method:或者更确切地说是一个可重用的 CSS 类和 jQuery 的toggleClass()方法:

 jQuery( $ => { $(window).on('resize', function() { $("#side-pic").toggleClass("is-hidden", $(this).width() < 700); }); });
 .is-hidden {display: none;}
 <div id="side-pic">SIDE PIC</div> <script src="//code.jquery.com/jquery-3.1.0.js"></script>

You can also write a code Like following您也可以编写如下代码

$(document).ready(function(){
    $(window).resize(function(){

        if($(window).width() < 700) {
            $("#side-pic").hide();


        } else if($(window).width() >= 700){

            $("#side-pic").show();
        }

    });
});

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

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