用javascript修改时,onchange不会触发 [英] onchange doesn't fire when modified by javascript

查看:109
本文介绍了用javascript修改时,onchange不会触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用频谱(jQuery的频谱( https://github.com/bgrins/spectrum )彩色调色板插件. 我的目标是在用户浏览不同颜色时将颜色直接应用到背景上.

I am using spectrum (https://github.com/bgrins/spectrum), a jQuery plugin for color palletes. My goal is that the color is being directly applied on the background, while the user is browsing the different colors.

到目前为止,我是这样的:

What I have so far is this:

//*****Part of a 3rd party file, which I cannot modify****
$("#picker1").spectrum({
    allowEmpty:true,
    color: "#ECC",
    showInput: true,
    preferredFormat: "hex",
}); 
//***********************************


$("#picker1").on("change keyup paste", function(){
    newcolor=$("#picker1").val();
    $(".menu-itempreview").css("background-color", newcolor);     
});



<ul id="menu-primary-menupreview" class="someclass">
    <li class="menu-itempreview">Home</li>
    <li class="menu-itempreview">Sample Page</li>
    <li class="menu-itempreview">Uncategorized</li>
</ul>


<input type='input' id="picker1" />

在这里指点我: http://jsfiddle.net/h4Lc5b6a/

问题是,仅当用户单击提交"按钮时,颜色才会更新. 我将如何做到这一点,以便在用户浏览不同颜色时动态更新背景?

The problem is, that the color only updates when the user hits the submit button. How would I be able to make it, so that the background updates on the fly, while the user is browsing the different colors?

似乎问题出在onchange上,当用javascript修改输入字段时,该问题不会触发.

It seems the problems lies with the onchange, which doesn't fire when the input field is being modified by javascript.

推荐答案

您可以使用move回调( http://bgrins.github.io/spectrum/#events-move ).
添加到您的频谱初始化中:

You can use the move callback (http://bgrins.github.io/spectrum/#events-move).
Add to your spectrum initialization:

$("#picker1").spectrum({
    //...,
    move: function(color) {
        $(".menu-itempreview").css("background-color",  color.toHexString());
    }
}); 

在频谱初始化之后,您还可以使用:

Also you can use this after the spectrum initialization:

// Alternatively, they can be added as an event listener:
$("#picker").on('move.spectrum', function(e, tinycolor) { });
$("#picker").on('show.spectrum', function(e, tinycolor) { });
$("#picker").on('hide.spectrum', function(e, tinycolor) { });
$("#picker").on('beforeShow.spectrum', function(e, tinycolor) { });

这篇关于用javascript修改时,onchange不会触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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