【问题标题】:Checking for href attribute of a hovered link检查悬停链接的 href 属性
【发布时间】:2016-10-17 04:32:58
【问题描述】:
我有一组带有特定类的背景图像的链接。
a(href="some-url" style="background-image: image-url").location-thumb
我正在使用 Jquery 悬停功能来检查哪个链接已悬停并相应地想要更改相邻列中的背景。
我特别需要检查链接的href属性。
我需要如下 if 循环格式的语法:
if(hovered link attribute = "www.google.com"){
//proceed further
}
【问题讨论】:
标签:
javascript
jquery
css
【解决方案1】:
非常感谢您的回复。最后实现了代码,在带有链接的图像上打开和关闭悬停,不同的谷歌地图被设置为 iframe 元素。
$('a.location-thumb').hover(function(){
if($(this).attr("href") == "/2013/01/20/30-shali-tibba.html"){
document.getElementById('iframe1').src = "https://www.google.com
/maps/embed1"
}
}, function(){
document.getElementById('iframe1').src = "https://www.google.com
/maps/embed2"
});
【解决方案2】:
您可以像这样使用attribute selector:
$(document).ready(function() {
$('a[href="#hover"]').hover(
function() {
$(this).css('background-image', 'url("http://lorempixel.com/300/300/nature")')
}, function () {
$(this).css('background-image', 'url("http://lorempixel.com/300/300/sports")')
}
)
})
a {
display: block;
background: url('http://lorempixel.com/300/300/sports') no-repeat center;
width: 300px;
text-align: center;
line-height: 300px;
font-weight: bold;
font-size: 3em;
color: white;
text-shadow: 0 0 6px black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#hover">Hover Me</a>
【解决方案3】:
使用 jQuery,您可以在用户将锚点悬停在给定类上时进行监听,并检查其 href 属性是否与所需或所需的 URL 匹配,如果匹配则执行任意逻辑。这是三个不同的样本。第一个检查锚点是否指向特定的 URL。第二个检查链接中是否包含特定字符串,第三个检查链接是否与数组中的一组 URL 匹配。
//option 1 -the hovered link is an exact match to a string
$("a.location-thumb").hover(function() {
if ($(this).attr("href") === "http://www.google.com") {
alert("Yes")
//add whatever
$("#some-id").css("background-color", "crimson");
}
}, function() {
$("#some-id").css("background-color", "orange");
/*this is called when the user stops hovering*/});
//option 2: the hovered link includes a particular keywords in it
$("a.location-thumb").hover(function() {
if ($(this).attr("href").indexOf("google.com") !== -1) {
alert("Yes")
}
}, function() {/*mouseleave*/});
//Option 3: the hovered link points to one of several websites
var urls = ['http://www.google.com', 'http://facebook.com'];
$("a.location-thumb").hover(function() {
if (urls.indexOf($(this).attr("href")) !== -1) {
alert("Yes")
}
}, function() {/*mouseleave*/});
使用 Vanilla JavaScript,您可以执行以下操作:
var specialAnchors = document.getElementsByClassName("location-thumb");
for (var i = 0; i < specialAnchors.length;i++ ) {
specialAnchors[i].addEventListener("mouseover", function() {
var href = this.getAttribute("href");
console.log("hi");
console.log(href);
if (href === "http://www.google.com") {
alert ("Yes");
}
})
specialAnchors[i].addEventListener("mouseleave", function() {
alert("Mouse left this place");
})
}