簡體   English   中英

JavaScript添加到CSS值

[英]Javascript adding to CSS value

我似乎無法在任何地方弄清楚! 所以我想在每次單擊另一個元素時刪除該元素的x百分比。 到目前為止,這是我有什么幫助嗎?

var more = document.querySelector(".more");
more.onclick = function(){
  document.querySelector("#moreinfo").style.marginLeft - "-5%";
}

您將必須將marginLeft的值存儲在變量中,對其進行數學運算,添加回百分比單位,然后將其應用於元素。 例如:

 more.onclick = function() { var moreInfo = document.getElementById('moreInfo'); var marginLeft = moreInfo && parseInt(moreInfo.style.marginLeft, 10); if (marginLeft) { moreInfo.style.marginLeft = (marginLeft - 5) + '%'; } } 
 <div id="more-info"></div> 

使用getComputedStyle:

  var more = document.querySelector(".more"); more.onclick = function() { let moreinfo = document.querySelector("#moreinfo"); moreinfo.style.marginLeft = parseFloat(window.getComputedStyle(moreinfo).marginLeft) * 0.95 + 'px'; }; 
 <button class="more">click me</button> <div id="moreinfo" style="background: pink;width:100px;margin-left: 200px">boxes</div> 

您需要使用getComputedStyle()來獲取未通過內聯style屬性設置的樣式的樣式信息。

另外,根據您的HTML設置方式,百分比可能不起作用。

最后,您必須獲得當前的margin-left ,提取其中的數字部分,使用該數字進行數學運算,然后將其連接起來以創建有效的屬性值。

 var more = document.querySelector(".more"); more.onclick = function(){ var currentLeftMargin = getComputedStyle(more).marginLeft; console.log(currentLeftMargin); // Element's style = number portion of current style, then do math, then add back on the unit more.style.marginLeft = (parseInt(currentLeftMargin, 10) - 5) + "px"; } 
 .more { background-color:yellow; margin:50px; height:50px; text-align:center; } 
 <div class="more">Click Me Over and Over</div> 

這是jQuery的方式:

$('.more').click(function(){

  // get the current margin-left value, convert to integer and store it as a variable 
  var marginLeft = parseInt($(".post-text").css('margin-left'));

  // then update the margin-left style, subtracting 5 from the current
  $("#moreinfo").css('margin-left', (marginLeft - 5) +'%')

})

您可以使用UltraPlugin.js函數: var myElement = document.GetElementById(element); myElement.onclick = css("myElement {css code here}"); var myElement = document.GetElementById(element); myElement.onclick = css("myElement {css code here}");

超插件

 document.getElementById("#moreinfo").style.marginLeft - "-5%";

取代這個

暫無
暫無

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

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