2016-04-25 125 views
1

我想用jQuery交換背景。但問題是,它沒有成功切換到新的背景,相反,舊的被刪除,我得到一個白色的背景。懸停交換背景

我一直在谷歌搜索,並嘗試把路徑作爲一個變種,而不是例如,和其他一些不成功的建議。

我的jQuery函數如下所示:

$("#btn").hover(function() { 
    $('#page1').css('background-image','url(../images/bg1_normal.jpg)'); 
}); 

而我的默認背景CSS是這樣的:

#page1 { 
    height: 100vh; 
    max-height: 100vh; 
    background-image: url("../images/bg1_rw.jpg"); 
    background-repeat: no-repeat; 
    background-size: 100%; 
} 

我使用Java Play Framework和圖片是在同一文件夾,因爲默認背景有效,所以它是正確路徑

編輯:我試過以及從web使用img源碼,只是爲了100%確定它不是路徑的一些問題,但它仍然只是使它變白。

+0

當然,我發現後立即意識到:P – Coleman

回答

1

嘗試.addClass和.removeClass功能 - 它很簡單,所有的工作作風是完成樣式表文件:

$("#btn").on({ 
    mouseenter : function() { 
     $('#page1').addClass('inverted'); 
    }, 
    mouseleave : function() { 
     $('#page1').removeClass('inverted'); 
    } 
}); 

,然後簡單地添加

#page1.inverted { 
    //style as you need 
} 

到您的樣式表。

+0

好和易於修復,謝謝! –

2

我相信當鼠標離開時,jQuery的hover()函數不能刪除特定的樣式。

你可能只是做自己

$("#btn").on({ 
    mouseenter : function() { 
     $('#page1').css('background-image','url(../images/bg1_normal.jpg)'); 
    }, 
    mouseleave : function() { 
     $('#page1').removeAttr('style'); 
     // or simply set the backround again to the other image 
    } 
}); 
+0

它使它至少在鼠標離開時回到正常的背景,但只有在輸入時才切換到白色背景。 –

+0

如果圖像是它應該是的地方,它不應該這樣做 – adeneo

+0

這很奇怪,我100%肯定它是圖像的正確路徑,它在那裏。檢查它至少10次,因爲這是我首先想到的。 –

0

如果您使用的圖像,你可以做一個形象的交換這樣

https://jsfiddle.net/RachGal/oee3guxz/

$("#flowers").mouseover(function() { 
 
    var _this = $(this); 
 
    var current = _this.attr("src"); 
 
    var swap = _this.attr("data-swap"); 
 
    _this.attr('src', swap).attr("data-swap", current); 
 
    _this.toggleClass("opaque"); 
 
});
.opaque { 
 
    opacity:.5; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> 
 
<img id='flowers' class="full" src='http://www.rachelgallen.com/images/snowdrops.jpg' width="500" height="400" data-swap='http://www.rachelgallen.com/images/daisies.jpg' width="500" height="400" />

或如果你可以只使用co LOR這樣

$("#color").mouseleave(function() { 
 
     $("body").css("background-color","black"); 
 
}); 
 
$("#color").mouseover(function(){ 
 
     $("body").css("background-color","red"); 
 
}); 
 
$("#color").click(function(){ 
 
    $("body").css("background-color","green"); 
 
});
body, #color { 
 
    height: 800px; 
 
    width: 800px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<div id="color">&nbsp;</div>

https://jsfiddle.net/RachGal/8p783jfo/

希望這有助於

瑞秋

+0

第二個工作在兩個懸停和點擊 –