基于< option>将背景更改为图片.价值选择 [英] Changing the background to a picture based on an <option> value selection

查看:196
本文介绍了基于< option>将背景更改为图片.价值选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我知道这个问题以前也很相似,但是我没有在该提要中找到答案,因为答案不能与我的其他JavaScript一起使用. 这是我的问题.我正在尝试添加菜单以更改正在处理的表单上的背景.当从<select>字段中选择<option>时,我无法弄清楚如何使背景变为图像.我想仅用JavaScript来完成此操作,但是如果需要的话,我将使用JQuery.

So I know this question was, very similarly asked before, however I did not find the answer in that feed as the answer did not work with my other JavaScript. Here's my problem. I am trying to add in a menu to change the background on a form I am working on. I cannot figure out how to make the background change to an image when an <option> is selected from the <select> field. I would like to accomplish this with just JavaScript, but I will use JQuery if need be.

<label for="pictype">Select a New Background</label>
<select id="pictype" name="pictype" onclick="picchange()">
    <option value="p1">pic1</option>
    <option value="p2">pic2</option>
    <option value="p3">pic3</option>
    <option value="p4">pic4</option>
    <option value="p5">pic5</option>
    <option value="p6">pic6</option>
</select>

推荐答案

您可以使用.change事件和智能文件命名来实现此结果.到目前为止,使用jQuery是最简单的解决方案.

You can use a .change event, and smart file naming to achieve this result. Using jQuery is by far the easiest solution.

如果将图像命名为与选项值相同的名称,则可以基于所选的当前选项来引用图像.因此,对于第一个选项,您可以将图片命名为p1.jpg.

If you name your images the same as the option values, you can then reference images based off of the current option selected. So for the first option you could name the picture, p1.jpg.

<label for="pictype">Select a New Background</label>
    <select id="pictype" name="pictype">
    <option value="p1">pic1</option>
    <option value="p2">pic2</option>
    <option value="p3">pic3</option>
    <option value="p4">pic4</option>
    <option value="p5">pic5</option>
    <option value="p6">pic6</option>
    </select>

jQuery

 $("#pictype").change(function(){
    var imageFileName = $(this).val();
    $("body").css("background-image", "url(../Images/"+imageFileName+".jpg)");    
});

因此,如果您选择了选项#1,则会将背景图片的url设置为url("../Images/p1.jpg");

So if you selected option #1, it would set the background image url to url("../Images/p1.jpg");

这是jsfiddle: http://jsfiddle.net/mtruty/3L2uP/ 希望这会有所帮助!

Here is the jsfiddle: http://jsfiddle.net/mtruty/3L2uP/ Hope this helps!

这篇关于基于&lt; option&gt;将背景更改为图片.价值选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆