Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
824 views
in Technique[技术] by (71.8m points)

jquery - Hide div if screen is smaller than a certain width

I want to hide a floating div if the user screen is < 1024px as it will overlay with my blog content area. I found this jQuery on the net but I am not sure how to use it.

$(document).ready(function() {

if ((screen.width>1024)) {
    // if screen size is 1025px wide or larger
    $(".yourClass").css('display', 'none'); // you can also use $(".yourClass").hide();
}
elseif ((screen.width<=1024))  {
    // if screen size width is less than 1024px
    $(".yourClass").css('display', 'block'); // here you can also use show();
}
});

If my floating div class name is sharecontent, should I replace the above script like below? If yes, it's not working.

$(document).ready(function() {

if ((screen.width>1024)) {
    // if screen size is 1025px wide or larger
    $(".sharecontent").css('display', 'none'); // you can also use $(".yourClass").hide();
}
elseif ((screen.width<=1024))  {
    // if screen size width is less than 1024px
    $(".sharecontent").css('display', 'block'); // here you can also use show();
}
});

I also tried replacing the screen.width with window.width but still no success :(

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use media queries. Your CSS code would be:

@media screen and (max-width: 1024px) {
    .yourClass {
        display: none !important;
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...