繁体   English   中英

Javascript onChange影响CSS样式

[英]Javascript onChange affecting CSS styles

我正在尝试创建一个“实时”视图,我们的客户可以在其中编辑将嵌入到自己的页面中的php页面的颜色。

通过在每个文本字段中输入一个十六进制值,它应立即更改为其相对div设置的背景色值。

<!--Enter a hex color to change the background of id="box1" -->
<input name="color1" id="color1" type="text" size="6" maxlength="6" onchange="DOTHIS(change background color of 'box1' to this value);"  />
<br />

<!--Enter a hex color to change the background of id="box2" -->
<input name="color2" id="color2" type="text" size="6" maxlength="6" onchange="DOTHIS(change background color of 'box2' to this value);"  />
<br />

<!--Enter a hex color to change the background of id="box2" -->
<input name="color3" id="color3" type="text" size="6" maxlength="6" onchange="DOTHIS(change background color of 'box3' to this value);"  />

<hr />

<div id="box1" style="background-color:#ff0000">HELLO 1</div>
<div id="box2" style="background-color:#00ff00">HELLO 2</div>
<div id="box3" style="background-color:#0000ff">HELLO 3</div>

这对某人可能很简单,但是过了几天,我找不到正确的方法。

更新:

看到答案的方向后,我认为最好添加以下内容。

如果ID名称不相关怎么办?

例:

id="maincolor" -> affected id="hello"
id="fontcolor" -> affected id="world"
id="buttoncolor" -> affected id="foo"

这就是为什么我认为最好为每个元素内联javascript?

只能更改四种颜色,还有一个选项可以隐藏包含文本的各种div,一个复选框可以隐藏标题。

系统在这里: https : //www.overseasmortgagefinder.co.uk/affiliates/generator.php

正如您从左侧看到的那样,我们的用户可以自定义“采购系统”在其网站上的外观。

我想做的是在右侧创建一个“实时视图”窗口,而不是静态帮助指南。

这对我的目标是否更清楚?

好吧,这是一个使用jquery的相当动态的方法。

将输入ID的格式分别更改为color-box1color-box2color-box3

 <script type="text/javascript"> $(function() { // assigns a onChange event to all inputs with ids that start with "color-box" $("input[id^=color-box]").change(function () { // validate user's input here // if valid, grab id of changed input & remove the "color-" part var id = $(this).attr("id").split("-", 2)[1]; // set color of div using the id above $("div#"+id).css("background-color","#"+$(this).val()); }); }); </script> 

如果您需要纯JavaScript的解决方案,只需大喊大叫。

这个怎么样:

onchange="document.getElementById('box' + this.id.charAt(this.id.length - 1 )).style.backgroundColor = this.value;"

另外,您有两个</form>结束标记。 我要摆脱第一个。

不使用jQuery的解决方案:

  • 从输入中删除onchange ,因为onchange不会被触发,直到用户离开(模糊)该字段。
  • 为每个输入字段添加onkeyup="changeBackground(this)"

将此JavaScript函数添加到您的页面:

changeBackground = function(source) {
    if (/^[a-f0-9]{3}|[a-f0-9]{6}$/.test(source.value)) { // test for a valid hex color
        var boxId = source.id.replace('color', 'box');
        document.getElementById(boxId).style.backgroundColor = '#'+source.value;
    }
}

这是要测试的小提琴

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM