我正在尝试创建一个“实时” View ,我们的客户可以在其中编辑他们将嵌入到自己页面中的 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
正如您从左侧看到的那样,我们的用户可以自定义“采购系统”在他们网站上的外观。
我想做的是在右侧创建一个“实时 View ”窗口,而不是静态帮助指南。
我的目标是否更加清晰?
最佳答案
这是一个使用 jquery 的相当动态的方法。
将输入的 id 的格式分别更改为 color-box1
、color-box2
和 color-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 解决方案,请大喊..
关于影响 CSS 样式的 Javascript onChange,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7956138/