0

我在网页中有一个下拉列表,它当前所做的是显示在列表中选择的单个图像。

我想要实现的是,如果选择了一个部门,例如酒吧,它将显示一组酒吧图像而不是一个单独的图像,任何知道这样做的人吗?如果我选择另一个选项,例如大学,它将显示大学徽标的多个图像。

即使我将其用作下拉列表,是否还有一种方法可以将鼠标单击超链接添加到图像?

我认为这是可能的,但我找不到有关该主题的太多信息。

任何帮助都会很棒。

我的 HTML 代码:

<table border="0" cellspacing="0" cellpadding="0">
    <tr>
        <td width="100%">
            <form name="mygallery">
                <p>
                    <select name="picture" size="1" onChange="showimage()">
                        <option selected value="gfx/Marstons.jpg">Marstons pubs</option>
                        <option value="gfx/NorthUni.jpg" href="http://www.northumbria.ac.uk/">Northumbria University</option>
                    </select>
                </p>
            </form>
        </td>
    </tr>
    <tr>
        <td width="100%">
            <p align="center">
                <img src="gfx/Marstons.jpg" name="pictures" width="99" height="100">
        </td>
    </tr>
</table>

我的 Javascript

function showimage() {
    if (!document.images) return
    document.images.pictures.src = document.mygallery.picture.options[document.mygallery.picture.selectedIndex].value
}
4

1 回答 1

1

我不确定您的需求是什么,但您不能直接在选择选项上添加 href 属性。

如果您只想添加 url on you 选项以在用户选择它时将其应用到您的 img 上,您可以使用 html5 提供的 data-* 属性。

这是您根据请求提供的代码示例。

用于现场测试的 JS 小提琴:http://jsfiddle.net/BVAkh/1/

html部分:

<html>
  <head></head>
  <body>
    <table border="0" cellspacing="0" cellpadding="0">
    <tr>
        <td width="100%">
            <form name="mygallery">
                <p>
                    <select name="picture" size="1" onChange="javascript:showimage()">
                        <option selected value="gfx/Marstons.jpg">Marstons pubs</option>
                        <option value="gfx/NorthUni.jpg" data-href="http://www.northumbria.ac.uk/">Northumbria University</option>
                    </select>
                </p>
            </form>
        </td>
    </tr>
    <tr>
        <td width="100%">
            <p align="center">
              <img src="gfx/Marstons.jpg" name="pictures" width="99" height="100" />
          </p>
        </td>
    </tr>
</table>
      </body>
    </html>

Js部分:

function showimage() {
    if (!document.images) return;
    var selectedItem = document.mygallery.picture.options[document.mygallery.picture.selectedIndex];
    document.images.pictures.src = selectedItem.value;   

    if(selectedItem.getAttribute("data-href")) {
      document.images.pictures.onclick = function() {
        window.location.href = selectedItem.getAttribute("data-href");
      }
    }
    else {
      document.images.pictures.onclick = null;
    }  
}

但我认为你应该重新考虑形象变化。也许为您的 p 设置一个 id 并使用 innerHTML 更改内容。如果提供了 data-href,您将能够为<a></a>您的图像添加标签。

于 2013-01-14T14:30:24.620 回答