我有這個簡單的HTML結構jQuery的縮短功能
<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
在此先感謝。
什麼不行?你得到什麼錯誤? – Whymarrh
不確定這是否是一個問題,'$(this).css(「top」,top [valore]);'< - 那些花哨的引號。 –
'未捕獲的SyntaxError:在$(this).css(「top」,top [valore]);意外的標記ILLEGAL';''和'Uncaught ReferenceError:定義未定義' – mdash