duanji1610 2017-02-20 03:41
浏览 52
已采纳

onResize()在WordPress 4.7.2中不起作用

I'm trying to display the browser window width onResize(). I've read lots of posts about it but it still isn't working. The JavaScript never runs (The alert never shows up).

This method of using onResize="dispScreenWidth()" works fine in a Bootstrap site. I know that the get_template_directory_uri() path is correct. I just installed jQuery updater but that was no help.

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条回答 默认 最新

  • drnysdnnb2909701 2017-02-20 03:50
    关注

    Your function is out of scope.

    You're declaring the dispScreenWidth() function inside another function so when you call it with onResize, that function is unavailable.

    Try removing it from the jQuery(document).ready scope and putting it in the main scope.

    Something like this:

    jQuery(document).ready(function(){
        //do other stuff
    }); 
    
    function dispScreenWidth() {
        jQuery('#diag').css('display', 'inline');
        jQuery('#diag').html('');
        jQuery('#diag').append(window.innerWidth + ', ');
    
        alert('display');
    }
    

    Also, you can use jQuery's equivalent to onResize instead of putting it in the body tag.

    Like this:

    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');
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度