2013-08-19 41 views
1

我使用名爲「Spritely」的JS插件來爲背景圖像添加動畫。一切正常(背景正在移動)。但是當點擊一個div(sprite)時,我無法獲得一個被激活的函數。Spritely div .click不工作

(我有script.js,jquery和spritely包含在裏面)。

HTML只是2的div(#container的和#hills)

CSS

#container 
{ 
width:100%; 
height:100%; 
margin-left:auto; 
margin-right:auto; 
background-image:url(clouds.jpg); 
background-repeat:repeat-x; 
z-index:-3; 
position:absolute; 
} 
#hills 
{ 
width:100%; 
height:250px; 
background-image:url(hills.png); 
background-repeat:repeat-x; 
background-position:bottom; 
z-index:1; 
position:absolute; 
bottom:0px; 
} 

的JavaScript

$(document).ready(function() { 
$(hills).click(function(){ 
    alert("hey"); 
}); 
}); 
var hills; 

$(document).ready(function(){ 
var hills = document.getElementById('hills'); 
$(hills).pan({fps: 30, speed: 2, dir: 'left'}); 
}); 

回答

1

看起來你正在使用hills試圖不首先將元素添加到它,試試這個:

$(document).ready(function() { 
    var $hills = $('#hills'); 
    $hills.pan({fps: 30, speed: 2, dir: 'left'}); 
    $hills.click(function(){ 
     alert("hey"); 
    }); 
}); 

我也用這個清理了你的代碼。這裏不需要有兩個單獨的ready()。我正在使用jQuery選擇器#hills,因爲您仍然在使用jQuery的功能。我也緩存該對象,以便我們不必包裝相同的jquery對象兩次。

1

你有一個變量範圍問題(見我添加的註釋):

$(document).ready(function() { 
    $(hills).click(function() { 
     alert("hey"); 
    }); 
}); 
var hills; // Your click handler uses this variable, which is never set 

$(document).ready(function() { 
    //this "hills" variable, since you prefaced with "var", 
    // is local to this anonymous function, 
    // meaning the click handler can't see it. 
    var hills = document.getElementById('hills'); 
    $(hills).pan({ 
     fps: 30, 
     speed: 2, 
     dir: 'left' 
    }); 
}); 

爲什麼有兩個DOM準備好處理程序?爲什麼不喜歡這個組合它們:

$(document).ready(function() { 
    var hills = document.getElementById('hills'); 
    $(hills).pan({ 
     fps: 30, 
     speed: 2, 
     dir: 'left' 
    }); 
    $(hills).click(function() { 
     alert("hey"); 
    }); 
}); 

另一種選擇是具有第二DOM準備處理程序通過刪除var關鍵字使用全局變量:

$(document).ready(function() { 
    $(hills).click(function() { 
     alert("hey"); 
    }); 
}); 
var hills; 

$(document).ready(function() { 
    hills = document.getElementById('hills'); 
    $(hills).pan({ 
     fps: 30, 
     speed: 2, 
     dir: 'left' 
    }); 
}); 

或者乾脆完全消除全局變量。這些代碼片段只執行一次,所以緩存DOM元素沒有多少好處:

$(document).ready(function() { 
    $('#hills').click(function() { 
     alert("hey"); 
    }); 
}); 

$(document).ready(function() { 
    $('#hills').pan({ 
     fps: 30, 
     speed: 2, 
     dir: 'left' 
    }); 
});