IE javascript 设置 style.left 不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5938805/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
IE javascript setting style.left not working
提问by tftd
Hey,
I'm struggling setting a style attribute to a div that's created via javascript.
The flow is:
嘿,
我正在努力为通过 javascript 创建的 div 设置样式属性。流程是:
- The script loads
- It creates a
<div id="test">
- It sets attribute
style="top: 20px; left: 10px; margin: 0px; position: absolute;"
- 脚本加载
- 它创造了一个
<div id="test">
- 它设置属性
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:
所有其他浏览器都可以正常工作,但是当涉及到 IE 时,事情就无法正常工作了。如何在 IE 中设置这些样式属性?到目前为止,这段代码:
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.
我能够设置顶部、边距和位置。Style.left 是不可能的。
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)
@IE 不工作版本:7,8。(6、9下没试过)
回答by tftd
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! :)
经过几个小时的调试代码,我终于设法把它弄对了。问题是我有一个返回数字的变量。该变量是某些计算的基础,在设置 div.style.left 时使用。所以变量有时会返回导致痛苦的 NaN。:) 感谢大家的努力和花费的时间来提供帮助!:)
回答by Ferruccio
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.`
//应该可行!...有时IE需要字符串格式的'XXXpx'。这取决于 DOC 类型。`
回答by duri
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.className
并将所有 CSS 移动到 CSS 文件。
回答by kennebec
div.style.cssText="top: 20px; left: 10px; margin: 0px; position: absolute;"
remember that the div'es position is relative to its parent- some old IE's need the parent element position set to relative or absolute, depending on the doctype.
请记住,div 的位置是相对于其父元素的 - 一些旧的 IE 需要将父元素位置设置为相对或绝对,具体取决于文档类型。