Javascript - 动态改变绝对定位

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4249020/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 10:47:11  来源:igfitidea点击:

Javascript - dynamically change absolute positioning

javascriptjqueryhtmlcss

提问by Quadwwchs

I have an HTML page that has a div that is position absolutely. I'm trying to write some Javascript that would dynamically move the div down whenever some data before it is generated. I've been playing with the .css jquery function but it does not appear to be working. Any ideas on how this can be accomplished?

我有一个 HTML 页面,它有一个绝对位置的 div。我正在尝试编写一些 Javascript,它会在生成某些数据之前动态地将 div 向下移动。我一直在玩 .css jquery 函数,但它似乎不起作用。关于如何实现这一点的任何想法?

I have the following div that is positioned on my page with the styles below it.

我有以下 div,它位于我的页面上,其下方的样式。

<div id="MyControl">
     <%Html.RenderPartial("MyControl")%>
 </div>

#MyControlControl  {
    position:absolute;
    text-align:left;
    left:100px;
    top:900px;
}

In the main part of my html i'm building a dynamic table with records from a database. Whenever a new row is added I want to call some sort of Javascript to move the div down by 50 px. I've tried both javascript (document.getElementByID gives me an object expected error) and jquery .css function. I can't get either to work.

在我的 html 的主要部分,我正在构建一个包含数据库记录的动态表。每当添加新行时,我想调用某种 Javascript 将 div 向下移动 50 像素。我已经尝试了 javascript(document.getElementByID 给了我一个对象预期错误)和 jquery .css 函数。我也不能上班。

回答by Phrogz

Grab the position using jQuery and increment it.

使用 jQuery 获取位置并增加它。

var d = $('#mydiv');
// Move down by 50px
d.css({top:d.position().top+50+'px'});

回答by Bazzz

Can you not just add 50px to the top attribute?

不能只在 top 属性上加 50px 吗?

var myControl = document.getElementById("MyControl");
var oldTop = parseInt(myControl.style.top);
myControl.top = oldTop +50;

回答by Quadwwchs

If you know the number of units to move it down, you could achieve it using:

如果您知道将其向下移动的单位数,则可以使用以下方法实现:

var obj = document.getElementById('<div id>');
obj.style.height = '<new height><units>'; i.e. '15px';

Edit

编辑

I didn't see you were using jQuery until after I posted.

直到我发布后,我才看到您在使用 jQuery。

回答by FatherStorm

so. Assuming you have a div with rules

所以。假设你有一个带有规则的 div

div.fixed{
position:absolute;
top:10px;
left:10px;
}

and some javascript

和一些 javascript

...

...

$('.fixed').css('top','20px');

...

...

you've moved the absolute DIV with class .fixed to be 20 pixels from the top of the page.. we really need to see some actual code to help you out any better...

您已经将 class .fixed 的绝对 DIV 移动到离页面顶部 20 像素的位置。