2017-04-23 60 views
-6

当鼠标悬停在它上面而没有点击时,我尝试检查单选按钮。它是什么时候显示照片。我试图用JQuery来做到这一点,但我是初学者。鼠标悬停时检查单选按钮

+0

表明您是否尝试过的代码?在这里显示你的代码 –

+0

@DanielH不要要求在JS小提琴代码。在这里索取代码。外部链接可能会随着时间的推移而变得无效,而且这是他人必须经过的额外步骤才能提供帮助。真的,唯一一次应该使用小提琴或CodePen的时候,SO代码片段环境将不会运行被询问的代码。 –

+0

@ScottMarcus当然,谢谢! –

回答

1

<!DOCTYPE html> 
 
<html> 
 
<head> 
 
    <meta charset="utf-8"> 
 
    <meta name="viewport" content="width=device-width"> 
 
    <title>JS Bin</title> 
 
    <style> 
 
    </style> 
 
</head> 
 
<body> 
 
    <label> 
 
    <input type="radio" name="photo" data-image="http://placehold.it/350x150" class="radio-hover"> 
 
    Option - 1 
 
    </label> 
 
    
 
    <label> 
 
    <input type="radio" name="photo" data-image="http://placehold.it/250x150" class="radio-hover"> 
 
    Option - 2 
 
    </label> 
 
    
 
    <br> 
 
    
 
    
 
    <img src="http://placehold.it/350x150" class="photo1" alt=""> 
 

 

 
    <script src="https://code.jquery.com/jquery-3.1.0.js"></script> 
 
    
 
    <script> 
 
    $(".radio-hover").hover(function(){ 
 
     var imageUrl = $(this).data("image"); 
 
     $("img").show(); 
 
     $("img").attr("src",imageUrl); 
 
    },function(){ 
 
     $("img").hide(); 
 
    }); 
 
    </script> 
 
</body> 
 
</html>

+0

虽然此代码片段可能会解决问题,但[包括解释](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers)确实有助于提高帖子的质量。请记住,您将来会为读者回答问题,而这些人可能不知道您的代码建议的原因。 – jmattheis

1

你可以有无线电侦听mouseenter事件,此时你可以在当前的无线触发click事件,或明确电台的checked属性设置为true。请记住,收音机和复选框需要使用.prop()而不是.attr(),因为在HTML中它们在技术上没有价值,它们只是一个命名属性。

$(function() { 
 
    $(':radio').on('mouseenter', function() { 
 
    $(this).prop('checked', true); 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type="radio" name="radio-group" value="radio1"><br/> 
 
<input type="radio" name="radio-group" value="radio2"><br/> 
 
<input type="radio" name="radio-group" value="radio2"><br/>

+0

谢谢!你的代码给了我很多帮助!我改变它是这样的