开发者

How can I hide some ID elements using Javascript if the browser window is less than a given size?

开发者 https://www.devze.com 2023-03-07 00:18 出处:网络
I have been looking for an answer to this problem for hours and can\'t find anything that works. I need to make some elements if a web page not visible if the browser window width is less than a give

I have been looking for an answer to this problem for hours and can't find anything that works.

I need to make some elements if a web page not visible if the browser window width is less than a given size. This is because there are some fixed position "buttons" on the left side of the window which expand when rolled-over, BUT if the window is less than about 1056 pixels in width, the buttons overlap the main page contents.

I have a script for returning the window size and putting that value into a variable. I have got it to show a message if the variable value is less than 1056. (for testing)

I have seen ways how to 开发者_如何学编程make things visible or not with jQuery and and with Javascript but none of them work for me.

The id of the image I'm trying to hide is #go2.

here is a part of the script I have been trying to get to work:

if (viewportwidth <1056)document.write('<p>Your viewport width is LESS than 1056</p>');

if (viewportwidth <1056)document.getElementById('go2').style.display = 'none';

I have had to use {literal} tags as the pages are using SMARTY templates!

I am very new to javascript and jQuery and wouold appreciate any help.

Thanks.


To make sure that the behavior happens when the user resizes the window, you can also bind to the resize event:

jQuery(window).resize(function() {
   if(jQuery(window).width() < 1056) {
      jQuery(".hide-these").hide();
   }
});


You can do, with jQuery:

if(viewportwidth <1056) {
    $('.target').hide();
}

Also, you can hide the elements with CSS3, like so:

@media only screen and (min-width: 1056px) {
    #go2 {
        display:none;
    }
}


CSS3 media queries do what you want without Javascript, however browser support is pretty patchy: http://www.w3.org/TR/css3-mediaqueries/

Alternatively, you could use Javascript as you've suggested above, with the usual caveats about JS being turned on etc. JQuery makes it easier, if you like Javascript libraries: http://www.ilovecolors.com.ar/detect-screen-size-css-style/

If not, there are plenty of tutorials you can Google that explain how to query window size with Javascript.

0

精彩评论

暂无评论...
验证码 换一张
取 消