Make DIV invisible in CSS and JavaScript

孤人 提交于 2019-12-04 10:22:35

问题


I have managed to make a DIV tag invisible in JavaScript by setting the display to none and the visibility to hidden. It can be achieved with this class also:

.invisible {
    display: none;
    visibility: hidden;
}

Display none will ensure the DIV box is empty, and visibility hidden will ensure it isn't visible. The problem with this method is when I have scrollable DIVs or textareas with overflowing content, when you set display: none, some browsers will forget the scroll position for these elements. Is there a better way to make a DIV invisible without using the display property? I would rather not resort to using JavaScript to record the scroll position and such if possible.

EDIT:

I managed to solve it with your help, I applied the following:

.invisible {
    visibility: hidden;
    position: absolute;
    top: -9999px;
}

.visible {
    visibility: visible;
    position: static;
}

I tried left: -9999px, but this expands the vertical scrollbar in IE... I also wrapped my textarea in another DIV and applied the visible/invisible styles to that, because the textarea would lose its scroll position otherwise. I tested this in Chrome, Firefox, IE and Safari on my iPhone. Just a note, the DIV wrapped around the textarea didn't seem to help in FF, and the scrollbar still reset. But the scrollable DIVs are fine now. Thanks for your help!


回答1:


This would probably work:

.invisible {
    position: absolute;
    left: -9999px;
}

EDIT: I would take a look at the common helpers in the HTML5 Boilerplate code to explore other ways of making things disappear.




回答2:


You can just use visibility:hidden if you want the element to be invisible but still rendered. display:none will remove it entirely and cause the scroll behavior you mentioned.




回答3:


You can use a JQuery hide() method. $('#DivID').hide(); or $('.DivClass').hide();




回答4:


You can use jQuery to acheive the solution. If you want to totally hide/show the div, then u can use:

$('#my_element').show()
$('#my_element').hide()

And if you want that your div become invisible and its still existing in the page, then you can use efficient trick:

$('#my_element').css('opacity', '0.0');  // invisible Maximum
$('#my_element').css('opacity', '1.0');  // visible maximum



回答5:


Layout-wise, display:none takes it completely out of the rendering tree and into this netherworld limbo. It has no well-defined dimensions or position anymore.

If you need some placeholder for scroll position, I'd suggest using a placeholder element. Some zero-height DIV or maybe even an <a name="something""></a> would work.




回答6:


I rather use a fixed height and width (height:0; width:0;). Don't forget to eliminate borders, paddings and margins.



来源:https://stackoverflow.com/questions/5113246/make-div-invisible-in-css-and-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!