javascript - 向上滑动 div 以使用 jQuery 匹配其新内容

标签 javascript jquery

我有一个包含问题的 div

Questions 2: What is the square root of 16?

A. 7
B. 5
C. 4
D. 1

我需要这样做,以便在选择答案时,它会向上滑动并显示:

QUESTION 2: Correct! (Or Incorrect!)

我在这里使用 Javascript 来完成所有工作:

function finalizeAnswer(bttn,c,questionId) {
    if (c) {
        bttn.parentNode.style.backgroundColor="lightgreen";
        bttn.parentNode.innerHTML="<b>QUESTION "+(questionId+1)+":</b> Correct!";
    } else {
        bttn.parentNode.style.backgroundColor="pink";
        bttn.parentNode.innerHTML="<b>QUESTION "+(questionId+1)+":</b> Wrong!";
    }
    updateScore();
}

div 调整大小是因为它的内容不同(不再是一个长问题,只是一个简短的回答)。是否可以替换这里的某些东西,使其向上滑动而不是仅仅弹出?

仅供引用我包含的功能:

bttn -> The button that was pressed. (A, B, C, or D)

c -> If the answer was correct

questionId -> Used to get data about the question.

updateScore(); -> just a function that updates the score on the quiz.

最佳答案

该解决方案使用 jQuery 来实现高度变化的动画效果。

编辑:我已经更新了它以使用真正的新高度,而不是神奇地猜测的 24px。

<强> See Live Demo on jsFiddle

function displayResult(container, correct, questionId){ 

    // Keep up with the old height
    var oldHeight = $(container).height();

    // Change the contents
    $(container).css('background-color', correct == true ? 'lightgreen' : 'pink');
    $(container).html("<b>QUESTION " + (questionId+ 1) + ":</b> " + (correct == true ? "Correct!" : "Wrong!"));    

    // Capture the new height
    var newHeight = $(container).height();

    // Jump back to the old height and then animate to the new
    $(container).css('height', oldHeight);
    $(container).animate({height:newHeight});
}

function finalizeAnswer(bttn,c,questionId) {
    displayResult(bttn.parentNode, c, questionId);

    // I have commented out the call to updateScore since I don't have it
    //updateScore();
}

关于javascript - 向上滑动 div 以使用 jQuery 匹配其新内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5835735/

相关文章:

jquery - 在 jquery .click() 事件后重置背景颜色

javascript - jquery或js中优先排序

javascript - 尝试使用 socket.io 时出错

jquery - 仅为嵌套模态显示模态背景

javascript - 如何从类函数返回新的 Backbone 实例

javascript - jQuery:使用 $.each 传递的字符串

javascript - jQuery/JavaScript : Using a JavaScript array in jQuery

javascript - 在鼠标悬停时或以编程方式在传单 map 中突出显示 L.divIcon

javascript - 递归迭代器的最大调用堆栈大小错误

javascript - 是否可以指定来自 props 的数组长度?