[英]Making div invisible and visible using toggle in jQuery
我有一個div,當您單擊它時,它會變為不可見,而當您再次單擊它時,它會變為可見。 但是我的代碼出了點問題。 請看一下:
<div id = "id"> Hello </div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript">
//*****************************************************************************
function toggleOnClick($id){
$("#"+$id).click(function() {
$("#"+$id).toggle(
function () {
$(this).css({visibility: "hidden"});
},
function () {
$(this).css({visibility: "visible"});
}); //end of $("#"+$id).toggle
}); //end of $("#"+$id).click(function()
} //end of function toggleOnclick($id)
//*****************************************************************************
$(document).ready(function(){
toggleOnClick("id");
});
</script>
PS:我從這個鏈接中的可接受答案得到了我的資料: jQuery切換CSS?
tggle()
將在display
屬性之間切換,因此在隱藏元素后將不會保留元素的位置。您需要在回調中使用css()
並更新其opacity
,它將保留它的位置。
更新: click事件不會在具有visibility: hidden
元素上觸發visibility: hidden
因此您需要使用opacity:0
css()
中的回調是一個返回要設置的值的函數。 這是當前元素。 接收元素在集合中的索引位置和舊值作為參數。 (摘自http://api.jquery.com/css/#css-propertyName-function )
<div id="id">Hello</div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script type="text/javascript"> //***************************************************************************** function toggleOnClick($id) { $("#" + $id).click(function() { $("#" + $id).css('opacity', function(i, v) { return v == 0 ? 1 : 0; //end of $("#"+$id).toggle }); }); //end of $("#"+$id).click(function() } //end of function toggleOnclick($id) //***************************************************************************** $(document).ready(function() { toggleOnClick("id"); }); </script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.