簡體   English   中英

如何將樣式元素添加到div並使用javascript將其刪除

[英]How do I add a style element to a div and remove it using javascript

當用戶單擊按鈕觸發事件時,我想向div元素添加一個margin-left css樣式,然后在用戶再次單擊該按鈕時將其刪除。

這是div元素:

<div id="container" class="content">

JavaScript應該將其更改為:

<div id="container" class="content" style="margin-left:354px">

理想情況下,使用動畫使其看起來向左滑動而不是跳躍。

在事件偵聽器中嘗試以下操作:

var cont = document.getElementById("container");
cont.style.marginLeft = cont.style.marginLeft === "354px" ? "auto" "354px";

這沒有動畫。 您可以考慮為此使用CSS:

#container {
    transition: margin-left ease 500ms;
}

但是,如果您想支持較舊的瀏覽器和IE9,請尋求soyuka的答案。

在發布此類問題之前,您應該閱讀手冊

$('.content').animate({'margin-left':'354px'}, 1000); 
//where 1000 is the animation time in ms

回滾:

$('.content').animate({'margin-left':'auto'}); //or your previous value

嘗試這個解決方案,我已經加入了JSBin: http : //jsbin.com/oyemen/1/edit

您可以將jQuery.animatemargin-left css屬性一起使用。 animate的第二個參數是持續時間(以毫秒為單位)。 還有許多其他設置可以更好地控制動畫(例如,緩入或緩出)。

$('#container').animate({'margin-left':'354px'},3000); 

並將其移回相反的方向

$('#container').animate({'margin-left':'0px'},3000); 

實時示例: http//jsfiddle.net/xdpCs/1/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM