div和div之间画横线,如何在两个div之间画一条线?

I'm currently trying to draw a diagonal line between the bottom right corner of one div to the top right corner of another. If possible, I would like to do it without jQuery. Is this possible?

解决方案

This won't work with IE8 or below because of CSS limitations.

function getOffset( el ) {

var rect = el.getBoundingClientRect();

return {

left: rect.left + window.pageXOffset,

top: rect.top + window.pageYOffset,

width: rect.width || el.offsetWidth,

height: rect.height || el.offsetHeight

};

}

function connect(div1, div2, color, thickness) { // draw a line connecting elements

var off1 = getOffset(div1);

var off2 = getOffset(div2);

// bottom right

var x1 = off1.left + off1.width;

var y1 = off1.top + off1.height;

// top right

var x2 = off2.left + off2.width;

var y2 = off2.top;

// distance

var length = Math.sqrt(((x2-x1) * (x2-x1)) + ((y2-y1) * (y2-y1)));

// center

var cx = ((x1 + x2) / 2) - (length / 2);

var cy = ((y1 + y2) / 2) - (thickness / 2);

// angle

var angle = Math.atan2((y1-y2),(x1-x2))*(180/Math.PI);

// make hr

var htmlLine = "

//

// alert(htmlLine);

document.body.innerHTML += htmlLine;

}

The Distance Formula

Finding the Center Of Two Points

Finding the Angle Between Two Points

CSS Transform:Rotate

HTML Element offset[Width|Height|Top|Left] properties

Edit (for others with the same problem):

If you need to, for example, create a line from two corners that are not the top right and bottom right divs, go to this section of the code:

// bottom right

var x1 = off1.left + off1.width;

var y1 = off1.top + off1.height;

// top right

var x2 = off2.left + off2.width;

var y2 = off2.top;

where you see + off1.width and + off1.height, that means that the code is calculating the position of the bottom or the right of the div. Remove the + off1.width or the + off1.height to get the left or the top of the div.

EDIT updated to a more standard getOffset function. If you want to get really anal you'd probably also have to add document.documentElement.client[Left/Top] and walk the offsetParent tree, but I think getBoundingClientRect() and window.page[X/Y]Offset are sufficient for an example like this.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值