简体   繁体   中英

IE javascript setting style.left not working

Hey,
I'm struggling setting a style attribute to a div that's created via javascript. The flow is:

  1. The script loads
  2. It creates a <div id="test">
  3. It sets attribute style="top: 20px; left: 10px; margin: 0px; position: absolute;"

Everything works fine with all other browsers but when it comes to IE things just don't work. How can I set those style attributes in IE ? So far with this code:

var div = document.getElementById('test');
div.style.left     = "10px";
div.style.top      = "20px";
div.style.margin   = "0px";
div.style.position = "absolute !important";

I was able to set top, margin and position. Style.left is out of the question.

What's the best approach when dealing with style attributes in all browsers ?

@IE not working version: 7,8. (haven't tried it under 6 and 9)

After a couple of hours debugging the code I finally managed to get it right. The problem was I had a variable that returned numeric. That variable was the base of some calculation and it was used when setting div.style.left. So the variable sometimes returned NaN which caused the pain. :) Thanks to everybody for the effort and the time spent trying to help! :)

What's the best approach when dealing with style attributes in all browsers?

Setting just div.className and moving all CSS to CSS file.

div.style.cssText="top: 20px; left: 10px; margin: 0px; position: absolute;"

记住div'es位置是相对于它的父级 - 一些旧的IE需要将父元素位置设置为相对或绝对,具体取决于doctype。

function MuoveOnClickPosition(YourDIVObject) {

//numeric variables.
tempX = event.clientX;
tempY = event.clientY;

// String variables
var X, Y ;
X = tempX + 'px'; 
Y = tempY + 'px'; 

document.getElementById(YourDIVObject).style.left = X;
document.getElementById(YourDIVObject).style.top = Y;
}

//Should work !.. sometimes IE needs 'XXXpx' in string format. It depend on DOC Type.`

The !important is killing the position absolute. Does not even work in Firefox. Tested on JSBIN

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