javascript - 文本框内的可点击图标

标签 javascript jquery html css

我正在尝试在应该可点击的文本框中插入图像。看看我到目前为止编写的代码。我确实创建了一个类并向其中插入了背景图像。

现在,我的问题是如何让它可以点击?

$(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/

相关文章:

javascript - 如何从 jQuery 输入掩码插件文本框中删除下划线

javascript - 如何通过 Ajax 调用在元素上注册鼠标悬停

javascript - 循环嵌套数组并使用值渲染 div

javascript - jQuery 无法在 WordPress 网站上运行

javascript - 在 angularJs 中创建指令

javascript - 如何在没有nodeIntegration的情况下在index.html中使用node.js [ Electron ]

javascript - 如何将复杂的参数发送到asp.net

javascript - 事件类不随 javascript 函数改变

jquery - 提交按钮不适用于 html 代码

php - 如何将当前选项标记为选中?