[英]Changing display property using javascript messes up formatting
I part of a webpage that should only be shown if javascript is enabled. 我是网页的一部分,仅当启用javascript时才应显示。
I have tried the following: 我尝试了以下方法:
Method 1: I set the class to display: hidden;
方法1:我将类设置为
display: hidden;
then change it if javascript works by overriding it... 然后,如果JavaScript可以通过覆盖它进行更改,则对其进行更改...
<script type="text/javascript">
//<![CDATA[
$(document).ready(function() {
document.getElementById('only-show-if-js-enabled').style.display = 'block';});
//]]>
</script>
and also 并且
Method 2: I change the id to one has has display set as block (or auto)... 方法2:我将ID更改为已将显示设置为阻止(或自动)...
<script type="text/javascript">
//<![CDATA[
$(document).ready(function() {
$("#js-not-enabled").attr('id', 'js-enabled');
});
//]]>
</script>
Both methods seem to cause the actual formatting to be messed up, the first ignores my css that the list style is none, the second that overflow is hidden. 这两种方法似乎都导致实际的格式混乱,第一种方法忽略了我的CSS,即列表样式为none,第二种方法则隐藏了溢出。
What's going on? 这是怎么回事?
UPDATE: Rather embarrassingly I had overflow set to auto
, and just thought it was set to hidden. 更新:令人尴尬的是,我将溢出设置为
auto
,只是认为它设置为隐藏。 My mistake. 我的错。
Thank you for both replies though, they both shed some light on best practices etc. cheers. 不过,感谢您的两个答复,它们都使您对最佳做法等有所了解。
This should do it http://jsfiddle.net/kkwan/1/ 这应该做到这一点http://jsfiddle.net/kkwan/1/
$('#only-show-if-js-enabled').show();
Right, i kinda missed the whole issue here... Uhm, does the css work without the code you mentioned if you change the display: none;
是的,我有点想念整个问题……嗯,如果更改
display: none;
,css是否可以在display: none;
您提到的代码的情况下工作display: none;
to display: block;
display: block;
Or if you firebug it or something..? 或者,如果您对它进行纵火调试等等。
the modern approach for this kind of thing is to have you document ready function do this: 这种事情的现代方法是让您准备好文档功能来执行此操作:
<script type="text/javascript">
//<![CDATA[
$(document).ready(function() {
$("body").addClass("js");
//]]>
</script>
then in your CSS you can use this as a hook to only show things for JS-enabled (or disabled) devices. 那么在CSS中,您可以将其用作一个钩子,仅显示启用JS(或禁用)的设备的内容。
#OnlyShowWhenJsDisbaled { display: none; } /*hide by default */
body.js #OnlyShowWhenJsEnabled { display: block; } /*show when js has been confirmed*/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.