简体   繁体   中英

How do i pass a parameter as a percentage in DOM in a element.setAttribute in javascript?

better if viewed in img uploaded

function create(R,A){
  var B=R; 
  var C=A;          

  // if i define a number e.g. 50% it works but when i 
  //pass a value it doesn't
  img.style.top = "B%";             
  img.style.left = "C%";// same with c
}

Try this

function create(R,A){    
var B=R; 
var C=A;          

img.style.top = B + "%";            
img.style.left = C + "%";
}

Your code didn't work because you have passed "B%" for the style property which is not right. You should try B+ "%".

You can do like this

function create(R,A){    
img.style.top = R+"%";
//pass a value it doesn't.            
img.style.left = C+"%";
}

Also there is no need to create the variable unless you are modifying the parameters of the function

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