javascript - 下拉选择图片

标签 javascript jquery html css

我想创建一个下拉选择,其中包含图像而不是文本作为选项。我在 Stack Overflow 上进行了一些谷歌搜索和搜索,一般给出的答案是使用 jQuery combobox .

在我看来,此解决方案的问题在于您必须提供文本。看起来图像只是伴随左侧文本的图标。如果我错了请纠正我,但这个解决方案不会涵盖我正在尝试做的事情——用图像完​​全替换文本。

关于我正在尝试做的事情的一些背景信息——我正在尝试创建一个下拉菜单,供用户在在线绘画/涂鸦应用程序上选择线条粗细。图像将是不同粗细的线条,有点像 mspaint。

最佳答案

你甚至不需要 javascript 来做这件事!

我希望这能引起您的兴趣,所以就开始吧。一、html结构:

<div id="image-dropdown">
    <input type="radio" id="line1" name="line-style" value="1" checked="checked" />
    <label for="line1"></label>
    <input type="radio" id="line2" name="line-style" value="2" />
    <label for="line2"></label>
    ...
</div>

什么? 单选按钮? 正确。我们会将它们的样式设置为看起来像带有图像的下拉列表,因为这就是您想要的!诀窍在于知道当标签正确链接到输入(即“for”属性和目标元素 id)时,输入将隐式变为事件状态;单击标签 = 单击单选按钮。这是带有内联注释的略微缩写的 css:

#image-dropdown {
    /*style the "box" in its minimzed state*/
    border:1px solid black; width:200px; height:50px; overflow:hidden;
    /*animate the dropdown collapsing*/
    transition: height 0.1s;
}
#image-dropdown:hover {
    /*when expanded, the dropdown will get native means of scrolling*/
    height:200px; overflow-y:scroll;
    /*animate the dropdown expanding*/
    transition: height 0.5s;
}
#image-dropdown input {
    /*hide the nasty default radio buttons!*/
    position:absolute;top:0;left:0;opacity:0;
}
#image-dropdown label {
    /*style the labels to look like dropdown options*/
    display:none; margin:2px; height:46px; opacity:0.2; 
    background:url("http://www.google.com/images/srpr/logo3w.png") 50% 50%;}
#image-dropdown:hover label{
    /*this is how labels render in the "expanded" state.
     we want to see only the selected radio button in the collapsed menu,
     and all of them when expanded*/
    display:block;
}
#image-dropdown input:checked + label {
    /*tricky! labels immediately following a checked radio button
      (with our markup they are semantically related) should be fully opaque
      and visible even in the collapsed menu*/
    opacity:1 !important; display:block;
}

完整示例在这里:http://jsfiddle.net/NDCSR/1/

NB1:您可能需要在具有 position:relative +high z-index 的容器内将它与 position:absolute 一起使用。

NB2:当为单个线条样式添加更多背景时,考虑让选择器基于标签的“for”属性,如下所示:

label[for=linestyle2] {background-image:url(...);}

关于javascript - 下拉选择图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9508029/

相关文章:

jquery - 使用 jquery 在 div 中添加和删除样式属性

javascript - 将基于 Promise 的 React 应用程序转换为 redux-saga : how do I set React component variables?

javascript - Jquery 无法返回动画菜单列表上的事件状态

javascript - 用于 JavaScript 的 UIWebView 或 WKWebkit?

javascript - 如何在加载 jQuery 时执行函数?

javascript - 如何将元素保持在 float 元素之下?

html - 微数据可以应用于任何类型的 HTML 元素吗?

javascript - 带有固定文本覆盖的 JQuery 横幅旋转器

javascript - 如何.隐藏这个div?

javascript - 使用 Morgan 和 Winston 进行日志记录 - 正在生成文件,但文件是空白的