[removed] not working

前端 未结 3 1237
死守一世寂寞
死守一世寂寞 2021-01-13 12:32

I can\'t seem to get window.onblur to work properly.

window.onblur = console.log(\'blur\');

When the listener is applied to the window, it

相关标签:
3条回答
  • 2021-01-13 12:54
    window.onblur = () => console.log( "blur" );
    
    0 讨论(0)
  • 2021-01-13 13:05
    window.onblur = function() { console.log('blur'); }
    
    0 讨论(0)
  • 2021-01-13 13:06

    Ryudice has told you what to do, but didn't explain why it didn't work your way. Understanding the mechanics of it will help you work out how to proceed further.

    The reason is that your original code is running the console.log('blur') command immediately, and using the return value of that call as the window onblur event.

    The return value of console.log() varies between browsers, but for the sake of argument, lets say it returns a boolean true value. This means that your original code is the equivalent of writing this:

    window.onblur = true;
    

    Which clearly isn't going to work as you expect.

    What you need is for window.onblur to be set to a function that will be called each time the onblur event is triggered. This is achieved by wrapping the code in a function() {}, as per Ryudice's answer.

    You can also achieve it in simple cases by not supplying the brackets on the function name you want to call. But this method only works if you don't have any arguments you want to pass to the function, so wouldn't be suited to your console.log example.

    Hope that helps. If you're still puzzled, there's lots of resources on the web. Try googling for phrases like "javascript passing functions as arguments", and see what comes up.

    0 讨论(0)
提交回复
热议问题