【发布时间】:2016-09-11 18:59:04
【问题描述】:
如何通过 Drupal 8 模块使用 jQuery? 我正在尝试在 drupal 8 网站上运行一些 jquery 代码。这是一个 div 动画,它在包装器中随机移动 div。 我添加了 JS 和 CSS 文件,它们都显示在源代码中。然后,我将“容器”的 Div ID 添加到 html.html.twig(是的,我先将其复制到我的主题文件夹中)-
{%
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 仍然没有出现..
【问题讨论】:
标签: javascript jquery html css drupal