2016-09-11 41 views
0

如何通過Drupal 8模塊使用jQuery? 我想要在drupal 8網站上運行一些jquery代碼。這是一個div動畫,它隨機移動包裝中的div。 我已經添加了JS和CSS文件,它們都顯示在源代碼中。然後,我已經添加了「容器」來html.html.twig的股利ID(是的,我複製到我的主題文件夾第一) -如何通過Drupal 8模塊使用jQuery代碼?

{% 
    set body_classes = [ 
    logged_in ? 'user-logged-in', 
    not root_path ? 'path-frontpage' : 'path-' ~ root_path|clean_class, 
    node_type ? 'page-node-type-' ~ node_type|clean_class, 
    db_offline ? 'db-offline', 
    theme.settings.navbar_position ? 'navbar-is-' ~ theme.settings.navbar_position, 
    theme.has_glyphicons ? 'has-glyphicons', 
    'container', 
    ] 
%} 

還增加一個div用於此。再次在html.html.twig

<js-bottom-placeholder token="{{ placeholder_token|raw }}"> //**Not part of my code just adding it for comparison. 
    <div class='fly'>TEST DIV, IF I MOVE I'M WORKING!</div> 

所以文件顯示在源和源也顯示容器的div ID已被添加。

下面是jQuery代碼,請記住,我已將它調整爲與Drupal 8一起使用,因此可能會出現語法錯誤或兩個錯誤。

$.extend(Drupal.theme, { 
    animateDiv: (function() { 
    ($('.fly')); }), 

*幾乎可以肯定的問題是在這裏^^^

makeNewPosition: function ($container) { 
    // Get viewport dimensions (remove the dimension of the div) 
    var h = $container.height() - 10; 
    var w = $container.width() - 10; 

    var nh = Math.floor(Math.random() * h); 
    var nw = Math.floor(Math.random() * w); 

    return [nh, nw]; 
}, 

animateDiv: function ($target) { 
    var newq = makeNewPosition($target.parent()); 
    var oldq = $target.offset(); 
    var speed = calcSpeed([oldq.top, oldq.left], newq); 

    $target.animate({ 
     top: newq[0], 
     left: newq[1] 
    }, speed, function() { 
     animateDiv($target); 
    }); 

}, 

calcSpeed: function (prev, next) { 

    var x = Math.abs(prev[1] - next[1]); 
    var y = Math.abs(prev[0] - next[0]); 

    var greatest = x > y ? x : y; 

    var speedModifier = 0.23; 

    var speed = Math.ceil(greatest/speedModifier); 

    return speed; 

} 



}); 

這裏的CSS代碼

.fly { 
width: 50px; 
height:50px; 
background-color: red; 
position:fixed; 

} 

那就是我已經試過,但還是有沒有jQuery的活動,我我也嘗試過使用不同類型的類名(.div代替#div等),我認爲這是問題所在。飛行div顯示,但沒有風格,並沒有jQuery。我究竟做錯了什麼?

更新:在玩了一段時間的代碼後,我已經設法至少得到在div上顯示的樣式。 jQuery仍然沒有顯示雖然..

回答