如何检测是否打开和关闭<input type =“color”/>颜色选择器

时间:2016-02-23 16:44:35

标签: html html5 google-chrome

我有这样的颜色输入:

    override func viewDidLoad() {
    super.viewDidLoad()

    if SLComposeViewController.isAvailableForServiceType(SLServiceTypeFacebook){
        var facebookSheet:SLComposeViewController = SLComposeViewController(forServiceType: SLServiceTypeFacebook)


        facebookSheet.setInitialText("Hiya, I have just discovered this great app called Dwingle, which I think you're going to love.")
        let url = NSURL(string: "")
        facebookSheet.addURL(url)
        self.presentViewController(facebookSheet, animated: true, completion: nil)


        facebookSheet.completionHandler = {

            result -> Void in
            self.dismissViewControllerAnimated(true, completion: { () -> Void in
                self.navigationController?.popToRootViewControllerAnimated(true)
            })
        }


    } else {
        var alert = UIAlertController(title: "Accounts", message: "Please login to a Facebook account to share.", preferredStyle: UIAlertControllerStyle.Alert)
        alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
        self.presentViewController(alert, animated: true, completion: nil)
    }
}

我需要检测原生颜色选择器何时打开以及何时关闭。我正在为Chrome开发一个网络应用程序,但更喜欢更通用的解决方案。是否有任何事件因拣货员的开启和关闭而被解雇?

只要颜色选择器的颜色发生变化,就会触发更改事件,但我无法看到事件在打开时被触发。

2 个答案:

答案 0 :(得分:1)

颜色选择器docs表示输入事件适用。因此,您可以使用选择器上的focusblur事件执行某些操作,并监视专用变量的状态,如下所示:

工作fiddle

<强> HTML

<input id="clr" type="color" />

<强>的javascript

(function(){
    var picker = document.getElementById('clr'),
            tog = false;


  picker.addEventListener('focus', function(){
    if(tog === true){
        console.log('open');
    }else{
        console.log('closed');
    }
  });

  picker.addEventListener('blur', function(){
    tog = !tog;
    if(tog === true){
      tog = false;
        console.log('open');
    }else{
        console.log('closed');
    }
  });

}());

注意 focus事件触发两次。

答案 1 :(得分:0)

我不知道任何可以帮助您的API,我能想到的最好是使用clickchange个事件(但如果用户只是change将不会触发关闭颜色选择器而不做任何改变):

$("input").click(function () { console.log("opened"); });
$("input").change(function () { console.log("closed"); });

更新为了处理颜色选择器关闭而不做任何选择,您可以另外听取focusin(关闭颜色选择器后它会将焦点带回您的输入):

$("input").click(function () { 
    console.log("opened"); 
  window.colorPickerIsOpened = true; 
});
$("input").change(function () { 
  console.log("closed"); 
  window.colorPickerIsOpened = false; 
});
$("input").focusin(function () { 
    if (window.colorPickerIsOpened) { 
    console.log("closed"); 
    window.colorPickerIsOpened = false; 
  } 
});