我試圖在最初和當窗口調整大小時添加和刪除1em(16px)寬的段落元素。當腳本第一次加載時,它會在大多數情況下添加大約2到6個段落元素,當我調整窗口大小時,它會添加太多或刪除到很多,我不確定是什麼導致它超過或低於區別。我試圖用香草javascript來完成這個。在調整大小時添加和刪除元素
編輯:段落是爲了垂直,單個字符寬16px。然後,我會隨機產生不斷產生並落在屏幕上的字符。
(function(window, undefined){
var parentContainer = document.getElementsByClassName('stringFall_Container'),
paras = document.getElementsByClassName('para'),
containerWidth,
paraWidth,
difference,
paraAmount;
function checkContainerWidth() {
console.log('Running checkContainerWidth();')
containerWidth = parentContainer[0].offsetWidth;
console.log('The containers size is:' + containerWidth)
return true;
}
function checkParaWidth() {
console.log('Running checkParaWidth();')
paraWidth = paras[0].offsetWidth;
console.log('The Paragraphs size is:' + paraWidth)
return true;
}
function checkParaAmount() {
console.log('Running checkParaAmount();');
paraAmount = paras.length;
console.log(paraAmount);
return true;
}
function checkDifference() {
console.log('Running checkDifference();');
difference = containerWidth/paraWidth;
return true;
}
function addPara (number) {
console.log('Running addPara();');
number = number === undefined ? 1 : number;
console.log(number);
for (var i = 0; i < number; i++) {
var create = document.createElement('p');
parentContainer[0].appendChild(create).setAttribute('class', 'para');
}
return true;
}
function removePara (number) {
console.log('Running removePara()');
var lastElement = paras[paras.length - 1];
checkParaAmount();
number = number === undefined ? 1 : number;
for (var i = 0; i < number; i++) {
parentContainer[0].removeChild(lastElement);
}
return true;
}
function executeOnResize() {
checkDifference();
console.log('Running executeOnResize();');
checkContainerWidth();
if (difference < paraAmount) {
addPara(paraAmount - difference);
} else {
removePara(difference - paraAmount)
}
}
addPara();
checkContainerWidth();
checkParaWidth();
checkParaAmount();
checkDifference();
console.log(difference);
addPara(difference);
window.addEventListener('resize', executeOnResize, false);
})(this);
是否應該跨越容器寬度的段落,類名爲'stringFall_Container',覆蓋寬度的90-100%? –
我大概應該澄清一下吧?哈哈!段落實際上是垂直的,只有一個字符寬,最終我會隨機並不斷產生落在屏幕上的字符。 –