>喜欢在主题中。有些东西不起作用...我想将鼠标悬停在链接上并更改div 元素的背景图像。总是在数据菱形图像中设置的不同图片上。
<div id="img-nav-rhomboid" class="nav-rhomboid"></div>
<ul class="menu-list">
<li><a href="#" data-rhomboid-img="img/example1.jpg">A</a></li>
<li><a href="#" data-rhomboid-img="img/example2.jpg">B</a></li>
</ul>
.nav-rhomboid{
background: url(../img/nav-bg.png) no-repeat center center;
display: flex;
align-items: center;
}
$('li a').mouseover(function () {
var rhomboidImg = $(this).data('rhomboid-img');
$('#img-nav-rhomboid').each(function () {
$(this).css('background', $(this).attr(rhomboidImg));
});
});
尝试使用这行代码$('#img-nav-rhomboid').css('background', 'url(' + rhomboidImg + ') no-repeat');
$('li a').mouseover(function() {
var rhomboidImg = $(this).data('rhomboid-img');
$('#img-nav-rhomboid').css('background', 'url(' + rhomboidImg + ') no-repeat');
});
.nav-rhomboid {
background: url('http://s7d2.scene7.com/is/image/PetSmart/PB0101_HERO-Dog-Toys-20160818?$sclp-banner-main_large$') no-repeat center center;
display: flex;
align-items: center;
}
#img-nav-rhomboid {
height: 200px;
width: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="img-nav-rhomboid" class="nav-rhomboid"></div>
<ul class="menu-list">
<li><a href="#" data-rhomboid-img="https://images-na.ssl-images-amazon.com/images/G/01/img15/pet-products/small-tiles/23695_pets_vertical_store_dogs_small_tile_8._CB312176604_.jpg">A</a></li>
<li><a href="#" data-rhomboid-img="img/example2.jpg">B</a></li>
</ul>
你的jQuery代码中有一些错误,请检查下面的更新代码段:
$('li a').mouseover(function () {
var rhomboidImg = $(this).data('rhomboid-img');
$('#img-nav-rhomboid').css('background', 'url('+rhomboidImg+') no-repeat');
});
.nav-rhomboid{
background: url(../img/nav-bg.png) no-repeat center center;
display: flex;
align-items: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="img-nav-rhomboid" class="nav-rhomboid"></div>
<ul class="menu-list">
<li><a href="#" data-rhomboid-img="img/example1.jpg">A</a></li>
<li><a href="#" data-rhomboid-img="img/example2.jpg">B</a></li>
</ul>
这将解决问题...供您参考:
1-通过css为div导航菱形分配高度和宽度
2-在您的js代码中,您缺少css行的一部分,您必须添加url((
3-您永远不需要循环使用ID的元素(这必须是唯一的(
4-使用正确的图像路径更新我的代码(我刚刚做了一个测试(
<div id="img-nav-rhomboid" class="nav-rhomboid"></div>
<ul class="menu-list">
<li><a href="#" data-rhomboid-img="images/back_release.jpg">A</a></li>
<li><a href="#" data-rhomboid-img="images/back_investors.jpg">B</a></li>
</ul>
<style>
.nav-rhomboid{
background: url(images/back_reset.jpg) no-repeat center center;
display: flex;
align-items: center;
min-height: 400px;
width: 100%;
}
</style>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script>
$('li a').mouseover(function () {
var rhomboidImg = $(this).data('rhomboid-img');
$('#img-nav-rhomboid').css('background', 'url('+rhomboidImg+')');
});