2017-02-20 38 views
0

我试图显示浏览器窗口宽度onResize()。我读了很多关于它的帖子,但它仍然无法正常工作。 JavaScript从不运行(警报从不出现)。onResize()不适用于WordPress 4.7.2

这种使用onResize =“dispScreenWidth()”的方法在Bootstrap站点中工作正常。我知道get_template_directory_uri()路径是正确的。我刚刚安装了jQuery更新程序,但这没有帮助。

functions.php 
<?php 
    function flashdatadesign_twentytwelve_credits() { 
     echo 'Website by <a href="http://example.com" title="example">';    
    } 
    add_action('twentytwelve_credits', 'mysite_twentytwelve_credits'); 

    wp_enqueue_script('bcscript', get_template_directory_uri().'/js/bcscript.js', array ('jquery'), NULL, true); 
?> 

header.php 
<body <?php body_class(); ?> onResize="dispScreenWidth()"> 
    <div id="page" class="hfeed site"> 
     <p id="diag"></p> // --- this is just to display window.innerWidth 
     <header id="masthead" class="site-header" role="banner"> 
     <hgroup> 
     ........... 
</body> 

bcscript.js 
jQuery(document).ready(function(){ 
    function dispScreenWidth() { 
     jQuery('#diag').css('display', 'inline'); 
     jQuery('#diag').html(''); 
     jQuery('#diag').append(window.innerWidth + ', '); 

     alert('display'); 
    } 
}); 

回答

1

你的功能超出范围。

您在另一个函数中声明dispScreenWidth()函数,因此当您使用onResize调用函数时,该函数不可用。

尝试从jQuery(document).ready作用域中删除它并将其放在主范围中。

事情是这样的:

jQuery(document).ready(function(){ 
    //do other stuff 
}); 

function dispScreenWidth() { 
    jQuery('#diag').css('display', 'inline'); 
    jQuery('#diag').html(''); 
    jQuery('#diag').append(window.innerWidth + ', '); 

    alert('display'); 
} 

此外,您还可以使用jQuery的相当于在onResize,而不是把它在body标签。

就像这样:!

jQuery(document).ready(function(){ 
    //do other stuff 
}); 

jQuery(window).on('resize', function(){ 
    dispScreenWidth(); 
}); 

function dispScreenWidth() { 
    jQuery('#diag').css('display', 'inline'); 
    jQuery('#diag').html(''); 
    jQuery('#diag').append(window.innerWidth + ', '); 

    alert('display'); 
} 
+0

的jQuery(窗口)。在( '调整',()的函数工作非常感谢 – fuey

相关问题