我有某種民意調查,您可以投票是和否,并根據投票創建一個投票圖表(通過在另一個具有設定寬度的 div 內創建兩個 div 并設定前兩個 div 的寬度為 YES 和總票數中沒有票)。您可以單擊此處查看該專案以更好地理解。
我希望它看起來像在 CSS 中一樣具有影片效果,transition: width 100ms linear;就像這里一樣:
<!DOCTYPE html>
<html>
<head>
<title>Document</title>
<style>
.poll{
height: 50px;
width: 300px;
background-color: black;
transition: all 300ms;
}
.poll:hover{
width: 500px;
}
</style>
</head>
<body>
<div class="poll"></div>
</body>
</html>
但是,每當我添加類似于我的 div 類的內容時,我都看不到任何變化。有問題的 div 是在這個函式中創建的:
function renderPoll(){
container.innerHTML=''; //reset container
let poll1 = document.createElement('div');
let poll2 = document.createElement('div');
poll1.classList.add('poll-attr');
poll2.classList.add('poll-attr');
let innerTextPoll = Math.round(calcPerc()); //calcPerc() calculates the percent of YES votes with the equation percentage = (100*NumberOfYES)/NumberOfVotes
poll1.style.width = calcPerc() '%';
poll2.style.width = 100-calcPerc() '%';
poll1.innerText = innerTextPoll '%';
poll2.innerText = 100-innerTextPoll '%';
container.appendChild(poll1);
container.appendChild(poll2);
}
我幾乎沒有足夠的經驗來解決這個問題,因此感謝任何輸入!
uj5u.com熱心網友回復:
根據您的代碼和@Noel Maróti 的回答,實際上您所要做的就是在將民意調查添加到容器后為民意調查設定影片間隔。
function renderPoll() {
container.innerHTML = ''; //reset container
let poll1 = document.createElement('div');
let poll2 = document.createElement('div');
poll1.classList.add('poll-attr');
poll2.classList.add('poll-attr');
let innerTextPoll = Math.round(calcPerc()); //calcPerc() calculates the percent of YES
poll1.innerText = innerTextPoll '%';
poll2.innerText = 100 - innerTextPoll '%';
container.appendChild(poll1);
container.appendChild(poll2);
var target_length = 300;
animation(poll1, 0, (calcPerc()) * target_length / 100);
animation(poll2, 0, (100 - calcPerc()) * target_length / 100);
}
function calcPerc() {
return 75;
}
function animation(elem, from, to) {
let id = null;
let width = from || 0;
var speed = 2.5;
requestAnimationFrame(frame);
function frame() {
if (width < to) {
width = speed;
elem.style.width = width "px";
requestAnimationFrame(frame);
}
}
}
renderPoll();
.poll-attr {
border: 1px solid blue;
height: 50px;
background: lightyellow;
}
.poll {
height: 50px;
width: 300px;
background-color: black;
transition: all 300ms;
}
.poll:hover {
width: 500px;
}
<div class="poll"></div>
<div id="container"></div>
uj5u.com熱心網友回復:
你可以像這樣輕松地做到這一點:
function animation () {
let id = null;
const elem = document.querySelector(".poll");
let width = 300; // default width
clearInterval(id);
id = setInterval(frame, 5); // changing the number will effect the speed of the animation
function frame() {
if (width == 500) { // if the width is 500px, then finish animation
clearInterval(id); // finish animation
} else {
width ;
elem.style.width = width "px";
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/532024.html
上一篇:洗掉h1后切換開關出現故障
