简体   繁体   中英

Javascript adding to CSS value

I can't seem to figure this out anywhere! So I want to remove x percentage to the element when another element is clicked EACH time. This is what I have so far, any help?

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

You would have to store the value of the marginLeft in a variable, perform your math on it, add back the percentage unit, and then apply it to the element. Ex:

 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> 

use 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> 

You need to use getComputedStyle() to obtain the style information for styles that are not set via an inline style attribute.

Also, depending on how you have your HTML set up, percentages may not work.

Finally, you have to get the current margin-left , extract the number portion of it, do math with that number and then concatenate back the unit to create a valid property value.

 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> 

This is the jQuery way:

$('.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) +'%')

})

You can use the UltraPlugin.js function: var myElement = document.GetElementById(element); myElement.onclick = css("myElement {css code here}"); var myElement = document.GetElementById(element); myElement.onclick = css("myElement {css code here}");

UltraPluginJs

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

取代这个

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM