Javascript style.top 和 style.left 不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12535383/
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
style.top and style.left not working
提问by pr-
I have a script written up that when a button is pressed, the formatdialog div gets resized. The problem is that I can't figure out why my javascript code does not work. I am able to resize the width and height, but for whatever reason, the top and left can't be adjusted.
我写了一个脚本,当按下按钮时,formatdialog div 被调整大小。问题是我不知道为什么我的 javascript 代码不起作用。我可以调整宽度和高度的大小,但无论出于何种原因,无法调整顶部和左侧。
It doesn't make sense to me what could be causing a problem. Firebug doesn't give me any errors. The javascript just resizes the width and height and ignores the top and left attributes. I am guessing that the css properties are causing a problem, I just don't know what.
什么可能导致问题对我来说没有意义。Firebug 没有给我任何错误。javascript 只是调整宽度和高度的大小并忽略顶部和左侧属性。我猜是 css 属性导致了问题,我只是不知道是什么。
css:
css:
#formatdialog {
display:none;
left:25%;
top:25%;
width:400px;
height:200px;
position:absolute;
z-index:100;
background:white;
padding:2px;
font:10pt tahoma;
border:1px solid gray
}
Javascript:
Javascript:
function FormatDialogResize(){
var elem = document.getElementById('FormatDialog');
elem.style.top = "10%";
elem.style.left = "10%";
elem.style.width = "600px";
elem.style.height = "500px";
}
I also tried:
我也试过:
function FormatDialogResize(){
var elem = document.getElementById('FormatDialog');
elem.style.top = 10+"%";
elem.style.left = 10+"%";
elem.style.width = "600px";
elem.style.height = "500px";
}
Thanks.
谢谢。
采纳答案by Sushanth --
Why is you class name missing the pascal casing for the element ID in the classId
为什么您的类名缺少 classId 中元素 ID 的 pascal 大小写
#formatdialog {
FormatDialog
You have a typo.
你有一个错字。
The element id is formatdialogbut you are trying to call FormatDialog
元素ID是formatdialog但你试图调用FormatDialog
var elem = document.getElementById('FormatDialog');
Your code should be like this:
你的代码应该是这样的:
<div id="formatdialog">
</div>
var elem = document.getElementById('formatdialog');
elem.style.top = "10%";
elem.style.left = "10%";
elem.style.width = "600px";
elem.style.height = "500px";
#formatdialog
{
left:25%;
top:25%;
width:400px;
height:200px;
position:absolute;
z-index:100;
padding:2px;
font:10pt tahoma;
border:1px solid gray;
background-color:orange;
}?
If you want to use Pascal casing make sure it is the same in elementId and class
如果要使用 Pascal 大小写,请确保它在 elementId 和 class 中相同
Check this Fiddle
检查这个小提琴
回答by Peter
I had a similar problem and discovered that setting .top would not work until after I set the element to "position: absolute" .
我有一个类似的问题,并发现设置 .top 直到我将元素设置为 "position: absolute" 之后才起作用。