用javascript渐进增强隐藏元素

时间:2022-09-06 08:15:24

I use Jquery toggle method to view a div when a button is clicked

我使用Jquery切换方法在单击按钮时查看div

$("button").click(function(){
    $("#divId").toggle();
});

Works fine but the initial value is set to be viewed or as the css property display:block so when the page initially loads the div is viewed and I have to click the button to close it.

工作正常,但初始值设置为查看或作为css属性显示:阻止所以当页面最初加载时,查看div,我必须单击按钮关闭它。

what other answers suggested is that I change the css property but I do not want that as that will hide the div and if the user had their javascript not working for any reason, that would not be good.

其他答案建议是我改变了css属性,但我不想那样,因为那会隐藏div,如果用户的javascript因为任何原因不起作用,那就不好了。

So I want to hide the div initially with javascript and then comes Jquery's toggle method working normally. I tried document.getElementById(divId).style.dsplay="none" and put it right before the toggle method, but that makes the toggle not work and just hides the div.

所以我想先用javascript隐藏div然后让Jquery的toggle方法正常工作。我尝试了document.getElementById(divId).style.dsplay =“none”并将其放在toggle方法之前,但是这使得切换不起作用并且只是隐藏了div。

2 个解决方案

#1


1  

You may set initial value to hide the div by this way:

您可以通过以下方式设置初始值以隐藏div:

$(document).ready(function(){
   $("#divId").hide();
   $("button").click(function(){
     $("#divId").toggle();
   });
});

After you click the button. it will toggle to open the page.

单击按钮后。它将切换到打开页面。

#2


1  

Try this to hide div on page load:

试试这个在页面加载时隐藏div:

$(document).ready(function(){
    $("#divId").hide(); //or .toggle()
});

[UPDATE]

Or if you have more advanced logic on click event and you want it to also run on load:

或者,如果您在click事件上有更高级的逻辑,并且您希望它也在加载时运行:

$(document).ready(function(){
    $("button").trigger('click');
});

#1


1  

You may set initial value to hide the div by this way:

您可以通过以下方式设置初始值以隐藏div:

$(document).ready(function(){
   $("#divId").hide();
   $("button").click(function(){
     $("#divId").toggle();
   });
});

After you click the button. it will toggle to open the page.

单击按钮后。它将切换到打开页面。

#2


1  

Try this to hide div on page load:

试试这个在页面加载时隐藏div:

$(document).ready(function(){
    $("#divId").hide(); //or .toggle()
});

[UPDATE]

Or if you have more advanced logic on click event and you want it to also run on load:

或者,如果您在click事件上有更高级的逻辑,并且您希望它也在加载时运行:

$(document).ready(function(){
    $("button").trigger('click');
});