Delay changing innerHTML text using jQuery

2019-02-25 12:57发布

问题:

So I've got a pretty simple button that basically toggles a form on and off - we'll be using this on our site since we're doing an update and would like feedback available on any page. Here's the jQuery I have so far:

<script>
// Toggle Button Text Change
$('#feedbackLink').hover(
    // Change HTML on mouseover
    function() {
        $(this).html('Send us a quick message!');
    },
    // Change back on mouseout
    function() {
        $(this).html('How can we improve this page?');
    }
);
// Toggle Button and Form
$('#feedbackLink').click(function() {
    // Hide feedback button
    $('#feedbackLink').toggle(500);
    // Display feedback form
    $('#feedbackForm').delay(501).toggle(250);
});
// Feedback Form
$('#cancel').click(function() {
    // Slides form from view when "CANCEL" is clicked
    $('#feedbackForm').toggle(500);
    // Fades original link back into view after a defined delay to allow for previous form to be hidden
    $('#feedbackLink').delay(501).toggle(75);
});
</script>

So my question is, how can I delay or fade in either the .hover call or the .html swap?

Thanks for the help.

P.S. - I know the code can be further optimized, I just like to get the functionality working first - then I go back and condense what I can.

回答1:

You can achieve this by using setTimeout():

var timeout;
$('#feedbackLink').hover(
    function() {
        clearTimeout(timeout);
        timeout = setTimeout(function() {
            $("#feedbackLink").html('Send us a quick message!');
        }, 2000); // change the HTML after 2 seconds
    },
    function() {
        clearTimeout(timeout);
        timeout = setTimeout(function() {
            $("#feedbackLink").html('How can we improve this page?');
        }, 2000); // change the HTML after 2 seconds
    }
);


回答2:

How about this:

   $(document).ready(function() {

      function changeText(){
        $("#myDiv").text('test')
      }

      setTimeout(changeText, 2000);

    });