我有一个在html页面上创建动画的JavaScript。在Meteor项目之外,动画效果很好,因为它只是html文件中包含的.js文件。我怎么能让它在Meteor上运行呢? javascript文件似乎根本不运行(它没有做任何事情)。 Meteor可以包含原始的javscript文件吗?如果是这样怎么样?该文件是纯JavaScript,没有助手或任何定义Meteor结构的东西。
missionPage.js
var TxtRotate = function(el, toRotate, period) {
this.toRotate = toRotate;
this.el = el;
this.loopNum = 0;
this.period = parseInt(period, 10) || 2000;
this.txt = '';
this.tick();
this.isDeleting = false;
};
TxtRotate.prototype.tick = function() {
var i = this.loopNum % this.toRotate.length;
var fullTxt = this.toRotate[i];
if (this.isDeleting) {
this.txt = fullTxt.substring(0, this.txt.length - 1);
} else {
this.txt = fullTxt.substring(0, this.txt.length + 1);
}
this.el.innerHTML = '<span class="wrap">'+this.txt+'</span>';
var that = this;
var delta = 300 - Math.random() * 100;
if (this.isDeleting) { delta /= 2; }
if (!this.isDeleting && this.txt === fullTxt) {
delta = this.period;
this.isDeleting = true;
} else if (this.isDeleting && this.txt === '') {
this.isDeleting = false;
this.loopNum++;
delta = 500;
}
setTimeout(function() {
that.tick();
}, delta);
};
window.onload= function() {
console.log('I m here');
var elements = document.getElementsByClassName('txt-rotate');
console.log(elements);
for (var i=0; i<elements.length; i++) {
var toRotate = elements[i].getAttribute('data-rotate');
var period = elements[i].getAttribute('data-period');
if (toRotate) {
new TxtRotate(elements[i], JSON.parse(toRotate), period);
}
}
// INJECT CSS
var css = document.createElement("style");
css.type = "text/css";
css.innerHTML = ".txt-rotate > .wrap { border-right: 0.08em solid #666
}";
document.body.appendChild(css);
};
missionPage.html
<template name="missionPage">
<div class="ui center aligned container">
<h3>Our story</h3>
<h1>This website is
<span
class="txt-rotate"
data-period="2000"
data-rotate='[ "not just the website", "simple.", "pure JS.",
"pretty.", "fun!" ]'></span>
</h1>
</div>
</template>
答案 0 :(得分:1)
您是否一直在阅读Guide to Meteor, specifically the section on app structure?如果没有,我会从那里开始。
回答你的问题:
Meteor可以包含原始JavaScript文件吗?
是
如果是这样的话?
有很多方法。您可以直接导入它:
import './txtRotate.js';
或者您可以将它放在client/compatibility目录中,它将在其他JS文件之前加载和执行。
最后,您的missionPage.js
文件中只应包含与MissionPage Template相关的代码,而不是TxtRotate
代码。将TxtRotate
移至其自己的文件(window.onload
部分除外),将其导入missionPage.js
,并在呈现模板时对其进行初始化:
import { Template } from 'meteor/templating';
import './txtRotate.js';
Template.missionPage.onRendered(function() {
this.$('.txt-rotate').each(function(i, element) {
var toRotate = $(element).data('rotate');
var period = $(element).data('period');
if (toRotate) {
new TxtRotate(this.get(0), JSON.parse(toRotate), period);
}
});
});
您拥有的另一个选项是将TxtRotate函数更改为reusable Blaze Component而不是独立函数。类似的东西:
<template name="missionPage">
<div class="ui center aligned container">
<h3>Our story</h3>
<h1>This website is {{> TxtRotate period="2000" rotate=words}}</h1>
</div>
</template>
在模板助手中定义words
。