JAVASCRIPT
嗨,新手在这里。因此,我具有以下功能,类似于冠军:
//To find the position of an element
function getPosition(el) {
var xPos = 0;
var yPos = 0;
while (el) {
if (el.tagName == "BODY") {
// deal with browser quirks with body/window/document and page scroll
var xScroll = el.scrollLeft || document.documentElement.scrollLeft;
var yScroll = el.scrollTop || document.documentElement.scrollTop;
xPos += (el.offsetLeft - xScroll + el.clientLeft);
yPos += (el.offsetTop - yScroll + el.clientTop);
} else {
// for all other non-BODY elements
xPos += (el.offsetLeft - el.scrollLeft + el.clientLeft);
yPos += (el.offsetTop - el.scrollTop + el.clientTop);
}
el = el.offsetParent;
}
return {
x: xPos,
y: yPos
};
}
所以当我调用getPosition时,我将数字作为这样的对象来获得:
>{x: 200, y: 500}
现在,我正在构建另一个函数来触发某个位置的事件,但是我不能正确调用getPosition数字...我尝试了数十种变体,当然我在这里遗漏了一些东西。下面是一个简单的函数,用于显示我呼叫职位编号的方式不正确:
function test () {
console.log(getPosition(img));//An image - getPosition identify it to be at {x:200,y:500}
if (getPosition(img) == (200,500)){
console.log('It is there!')
} else {
console.log('it is not there!')
}
};
我也在其他选项之间进行了尝试:
function test () {
console.log(getPosition(img));
var x = 200;
var y = 500;
if (getPosition(img) == {x,y}){
console.log('It is there!')
} else {
console.log('it is not there!')
}
};
和此:
function test () {
console.log(getPosition(img));
if (getPosition(img) == {x: 200,y: 500}){
console.log('It is there!')
} else {
console.log('it is not there!')
}
};
所以我只得到'它不在那里!',我尝试了许多不同的方法来找到一种比较成功的方法。
知道我在做什么错吗?
非常感谢,圣诞节快乐。
getPosition()
函数返回一个对象。因此,您必须检查对象x
和y
属性,以确保它们与所需属性相匹配。
最简单的方法是只在if
语句中分别检查x和y。这似乎是您要尝试执行的操作,但是通过尝试检查1条语句中的x和y属性,您只是略微使用了语法。
//To find the position of an element
function getPosition(el) {
var xPos = 0;
var yPos = 0;
while (el) {
if (el.tagName == "BODY") {
// deal with browser quirks with body/window/document and page scroll
var xScroll = el.scrollLeft || document.documentElement.scrollLeft;
var yScroll = el.scrollTop || document.documentElement.scrollTop;
xPos += (el.offsetLeft - xScroll + el.clientLeft);
yPos += (el.offsetTop - yScroll + el.clientTop);
} else {
// for all other non-BODY elements
xPos += (el.offsetLeft - el.scrollLeft + el.clientLeft);
yPos += (el.offsetTop - el.scrollTop + el.clientTop);
}
el = el.offsetParent;
}
return {
x: xPos,
y: yPos
};
}
test()
function test() {
var img = document.getElementById("the-image");
console.log(getPosition(img));
var imageLocation = getPosition(img);
if (imageLocation.x === 8 && imageLocation.y === 22) {
console.log('It is there!')
} else {
console.log('it is not there!')
}
};
<img id="the-image" src=""/>