[英]window.location.hash not working?
我有一個鏈接( index.html#services
)和一個<div id="services>
,當我單擊鏈接然后淡出時我試圖更改其背景顏色。我使用的是最新的jQuery和jQuery顏色插件,以及:
$(document).ready(function(){
if(window.location.hash === '#services') {
var service = $('#services');
var originalColor = service.css('background-color');
service.css('background-color', '#FFEE9F').animate({
'background-color': originalColor
}, 3000);
}
});
進行突出顯示,但不起作用。 有人知道為什么嗎?
該代碼僅在頁面加載時運行,而不在單擊帶有哈希的鏈接時運行。 嘗試直接從新的瀏覽器標簽中跟蹤鏈接( index.html#services
),它可能會起作用。 您需要做的就是在更改哈希后運行該代碼。 新的瀏覽器有一個onhashchange
事件-但在舊的瀏覽器上沒有這樣的事件。 對於舊的瀏覽器,您可以每隔一段時間輪詢一次hash屬性,以查看其是否已更改。
如果偶然在觸發該動畫的鏈接上具有特定的標識符(css類,id,名稱等),則可以添加click
偵聽器以運行該代碼。 例如:
function animateBackground() {
var service = $('#services');
var originalColor = service.css('background-color');
service.css('background-color', '#FFEE9F').animate({
'background-color': originalColor
}, 3000);
}
$(function () { // shortcut to $(document.ready)
$('.fade-bg').live('click', animateBackground);
animateBackground();
});
或使用
window.onhashchange = function(){
if(window.location.hash === '#services') {
var service = $('#services');
var originalColor = service.css('background-color');
service.css('background-color', '#FFEE9F').animate({
'background-color': originalColor
}, 3000);
}
};
取決於您定位的瀏覽器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.