如何在特定坐标中定位DIV?
2022-08-30 03:06:40
我想在特定坐标中放置DIV?我如何使用Javascript做到这一点?
将其和属性分别脚本化为距左边缘和上边缘的像素数。它必须具有left
top
position: absolute;
var d = document.getElementById('yourDivId');
d.style.position = "absolute";
d.style.left = x_pos+'px';
d.style.top = y_pos+'px';
或者将其作为一个函数来执行,以便您可以将其附加到诸如此类的事件中onmousedown
function placeDiv(x_pos, y_pos) {
var d = document.getElementById('yourDivId');
d.style.position = "absolute";
d.style.left = x_pos+'px';
d.style.top = y_pos+'px';
}
您不必使用Javascript来执行此操作。使用普通的旧css:
div.blah {
position:absolute;
top: 0; /*[wherever you want it]*/
left:0; /*[wherever you want it]*/
}
如果你觉得你必须使用javascript,或者正在尝试使用JQuery动态地做到这一点,这会影响类“blah”的所有div:
var blahclass = $('.blah');
blahclass.css('position', 'absolute');
blahclass.css('top', 0); //or wherever you want it
blahclass.css('left', 0); //or wherever you want it
或者,如果你必须使用常规的旧javascript,你可以通过id抓取
var domElement = document.getElementById('myElement');// don't go to to DOM every time you need it. Instead store in a variable and manipulate.
domElement.style.position = "absolute";
domElement.style.top = 0; //or whatever
domElement.style.left = 0; // or whatever