繁体   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