突出显示表单中的选定图像 - 使用Jquery?

Sea*_*ean 6 html forms jquery image highlight

我搜索了谷歌的答案,并找到了nada,所以即使是一个页面的链接显示如何做以下将非常感激.

基本上我有一个只有图像的形式

<form>
<input type="image" src="image.jpg" value="image_value">
<input type="image" src="image2.jpg" value="image_value2">
</form>
Run Code Online (Sandbox Code Playgroud)

我希望能够以某种方式突出显示用户选择的图像.当用户点击图像1时,即使只是图像1周围的轮廓也是完美的.

我已经在这个项目上使用Jquery了,所以如果有一个jquery解决方案,它将是最方便的.

bry*_*aun 13

一种可访问的方法是将单选按钮标签设置为像图像选择一样:

<form action="#" method="post">
    <input type="radio" class="radio" name="example" id="ex1" value="ex1" checked />
    <label for="ex1" class="label">Example 1</label>
    <input type="radio" class="radio" name="example" id="ex2" value="ex2" />
    <label for="ex2" class="label">Example 2</label>
</form>
Run Code Online (Sandbox Code Playgroud)

然后是CSS.如您所见,无线电本身隐藏的不透明度为0:

.radio {
    opacity: 0;
    position: absolute;
}
.label {
    background: url(http://i.imgur.com/mW6xr2I.png);
    text-indent: -999em;
    border: 10px solid white;
    width: 126px;
    height: 126px;
    display: block;
    float: left;
    margin: 10px;
}
input[type="radio"]:checked + label {
    border: 10px solid orange;
}
Run Code Online (Sandbox Code Playgroud)

以下是一个实例:http://jsfiddle.net/RH98R/

这有一个额外的好处,就是不依赖于jQuery(甚至是javascript)!

  • 作为目前已接受答案的人(我在5年前写过!),我同意这是一个更好的解决方案,应该是公认的答案. (2认同)

Ben*_*Lee 7

更新:请参阅bryanbraun的回答.他的好多了.


在HTML中,<input type="image">它只是一个以图像为面的提交按钮.我不认为这就是你想要的.您可能需要一个实际图像列表,单击该列表时,会根据"数据值"属性设置隐藏的表单值.所以你的HTML应该是这样的:

<form id="select-form">
    <img src="image.jpg" data-value="image_value">
    <img src="image2.jpg" data-value="image_value2">
    <input type="hidden" id="image-value" name="selected_image" value="">
</form>
Run Code Online (Sandbox Code Playgroud)

然后在你的javascript中,你想要突出显示图像并设置隐藏值,如下所示:

$('#select-form img').click(function() {
    // Set the form value
    $('#image-value').val($(this).attr('data-value'));

    // Unhighlight all the images
    $('#select-form img').removeClass('highlighted');

    // Highlight the newly selected image
    $(this).addClass('highlighted');
});
Run Code Online (Sandbox Code Playgroud)

最后,为CSS文件中的highlight类设置一些样式:

img.highlighted {
    border: 2px solid blue;
}
Run Code Online (Sandbox Code Playgroud)

  • @Sean,它不起作用,因为你把代码放在一起的方式有很多问题:你没有包含jQuery,你没有把click处理程序放在$(document).ready中,而你没有为样式块指定类型.我在这里纠正了这些问题:http://pastie.org/1297686 (2认同)