通过JavaScript,我想找出如何查找跨度和按钮是否处于触摸状态。我看到了一些东西,Element.getBoundingClientRect()。如果那样做,我该如何正确地做呢?
我已经尝试使用 Element.getBoundingClientRect() 但很可能没有正确使用它。
var span1 = document.getElementById("mySpan")
var button = document.getElementById("myButton")
if(touches(span1, button)){
...
}
答案 0 :(得分:1)
检查span
元素和button
元素(内联元素)是否彼此相邻。
var span = document.getElementsByTagName("span")[0]
var btn = document.getElementsByTagName("button")[0]
if(touches(span, btn)){
console.log('touching!')
}
function touches(span, btn) {
var rect1 = span.getBoundingClientRect();
var rect2 = btn.getBoundingClientRect();
if (rect1.right == rect2.left) {
return true;
}
}
<span>Span</span><button>Btn</button>
对于块元素,例如div
元素
var div1 = document.getElementsByTagName("div")[0]
var div2 = document.getElementsByTagName("div")[1]
if(touches(div1, div2)){
console.log('Touching!')
}
function touches(div1, div2) {
var rect1 = div1.getBoundingClientRect();
var rect2 = div2.getBoundingClientRect();
if (rect1.bottom == rect2.top) {
return true;
}
}
<div>Div 1</div><div>Div 2</div>
答案 1 :(得分:0)
getBoundingClientRect
是您想要的。
下面的代码是一个简单的示例。您可能需要添加其他逻辑。
var span1 = document.getElementById("mySpan")
var button = document.getElementById("myButton")
var clickMe = document.getElementById("clickMe")
var outer = document.getElementById("outer")
function touches(el1, el2) {
const r1 = el1.getBoundingClientRect();
const r2 = el2.getBoundingClientRect();
console.log(r1.right, r2.left);
if (r2.left - r1.right < 1) {
console.log('touching');
}
else {
console.log('not touching');
}
}
touches(span1, button);
clickMe.addEventListener('click', () => {
outer.classList.toggle('touch');
setTimeout(() => {
touches(span1, button);
},0);
});
.outer {
font: 14px Tahoma;
position: relative;
}
#mySpan {
background-color: red;
}
.touch #myButton {
margin-left: -4px;
}
<div id="outer">
<span id="mySpan">span</span>
<button id="myButton">Button</button>
<hr/>
<button id="clickMe">Click Me</button>
</div>
答案 2 :(得分:0)
从获取两个元素的客户端开始:
var span1 = document.getElementById("mySpan");
var button = document.getElementById("myButton");
var rect1 = span1.getBoundingClientRect();
var rect2 = button.getBoundingClientRect();
var overlap = (rect1.right == rect2.left || // right to left touching
rect1.left == rect2.right || // left to right touching
rect1.bottom == rect2.top || // bottom to top touching
rect1.top == rect2.bottom) // top to bottom touching
if(overlap){
// ... do your stuff
}
如果括号中的一个或多个表达式为真,则很感人。如果全部为假,则必须有重叠或没有接触。
How to check if an element is overlapping other elements?
从那里适应...
答案 3 :(得分:0)
根据对this question的第二个响应中的说明,使用纯Javascript,getBoundingClientRect()
是正确的方法。
看看下面的代码,这应该可以完成工作:
function touches(a, b) {
var aRect = a.getBoundingClientRect();
var bRect = b.getBoundingClientRect();
return !(
((aRect.top + aRect.height) < (bRect.top)) ||
(aRect.top > (bRect.top + bRect.height)) ||
((aRect.left + aRect.width) < bRect.left) ||
(aRect.left > (bRect.left + bRect.width))
);
}