我正在尝试在应该可点击的文本框中插入图像。看看我到目前为止编写的代码。我确实创建了一个类并向其中插入了背景图像。
现在,我的问题是如何让它可以点击?
$(document).ready(function(){
$('.icon').click(function(){
$('.text-here').innerHTML = "Please enter your username";
});
});
.icon{
background-image: url(http://directorzcut.com/modules/aqb/profile_mp3_player/templates/base/images/icons/popout.png);
background-repeat: no-repeat;
background-position: left;
cursor: pointer;
}
.text-box{
padding-left: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type = "text" class="icon text-box"/>
<p class="text-here"></p>
只有图标所在的区域才应该是可点击的,有没有简单的方法可以做到这一点?
提前致谢:)
最佳答案
如果我没理解错的话,你可以用 label
元素和指向输入的 for
指针包装 img
。
当您点击 label
时,input
将获得焦点。
我正在使用 pointer-events: none
在不点击元素的情况下禁用对 input
的关注。 (pointer-events
不跨浏览器 can I use )
另外,我修复了你的 js(.html()
而不是 .innerHTML =
)
$(document).ready(function(){
$('.icon').click(function(){
$('.text-here').html('Please enter your username');
});
});
.input-wrapper {
position: relative;
}
.icon {
position: absolute;
top: 50%;
left: 5px;
z-index: 1;
height: 10px;
margin-top: -5px;
}
.icon img {
display: block;
}
.text-box {
padding-left: 20px;
height: 30px;
width: 250px;
/*pointer-events: none;*/
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="input-wrapper">
<input id="textbox" type="text" class="text-box"/>
<label class="icon" for="textbox">
<img src="http://directorzcut.com/modules/aqb/profile_mp3_player/templates/base/images/icons/popout.png" />
</label>
</div>
<p class="text-here"></p>
关于javascript - 文本框内的可点击图标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41957225/