我有这个简单的html结构
<div id="img1" class="red">
<img src="#">
</div>
<div id="img2" class="red">
<img src="#">
</div>
<article>
<div class="text">
<h2><a href="" id="link1">This</a> is just a try to understand if i'm able to use this fukking stuff or i will <a href="" id="link2">suck</a> this time like many others</h2>
</div>
</article>
我正在尝试检索有关我的链接位置的一些信息,以便将该值传递给图像,以便以某种绝对的方式更改其初始位置。
这是我真正为我工作的jQuery。
function positioning() {
var number = 1 + Math.floor(Math.random() * 100);
var top1 = $("#link1").offset().top - number;
var top2 = $("#link2").offset().top - number;
var left1 = $("#link1").offset().left;
var left2 = $("#link2").offset().left;
var right1 = $(window).width() - (left1 + $("#link1").width());
var right2 = $(window).width() - (left2 + $("#link2").width());
if (left1 > ($(window).width()/2)) {
$("#img1").css({"top": top1, "right": right1 - number});
} else {
$("#img1").css({"top": top1, "left": left1 - number});
};
if (left2 > ($(window).width()/2)) {
$("#img2").css({"top": top2, "right": right2 - number});
} else {
$("#img2").css({"top": top2, "left": left2 - number});
};
};
但我不想为我的所有链接和图像重复所有这些内容,因为我会有更多。所以,我正在考虑某种方式来做到这一点,但它不起作用。这是我制作的代码。有人可以帮我理解哪些是我的错误?
var n = $("a[id*='link']").length;
var top = [];
var left = [];
var right = [];
var valore;
function positioning() {
$("a[id*='link']").each(function() {
for(var i = 0; i <= n; i++) {
top.push(this.offset().top);
left.push(this.offset().left);
right.push($(window).width() - (left[i] + this));
};
});
$("a[id*='img']").each(function() {
valore = this.id.slice(-1);
$(this).css("top", top[valore]);
if (left[valore] > ($(window).width()/2)) {
$(this).css("right", right[valore]);
} else {
$(this).css("left", left[valore]);
};
});
};
错误:
Uncaught SyntaxError: Unexpected token ILLEGAL
at $(this).css(“top”, top[valore]);
Uncaught ReferenceError: positioning is not defined
提前致谢。
答案 0 :(得分:0)
您引用的字符串top
引用了错误的引号“
”
,它们都应为"
。
替换
$(this).css(“top”, top[valore]);
与
$(this).css("top", top[valore]);
至于你的完整功能,你可以试试这个:
function positioning() {
var window_width = $(window).width();
$("[id^='link']").each(function(index, link) {
var $link = $(link);
var top = $link.offset().top;
var left = $link.offset().left;
var right = window_width - (left + $link.width());
var num = link.id.replace("link", "");
var $img = $("#img"+num);
$img.css("top", top);
if (left > window_width/2) {
$img.css("right", right);
} else {
$img.css("left", left);
};
});
}
我简化了它,它只使用一个循环,并且不需要数组来存储位置数据。