【问题标题】:Using Ajax to pull image into div, how do I add height to div before call, then remove it after image is loaded?使用 Ajax 将图像拉入 div,如何在调用前为 div 添加高度,然后在加载图像后将其删除?
【发布时间】:2014-04-30 21:30:16
【问题描述】:

我正在使用表单和 Ajax 动态拉取图像以替换 .results div 中的另一个图像。我的第一次尝试成功了,但是当图像被删除时页面跳了起来,当图像加载时又跳了回来。我想我可以添加样式属性来给 div 一个高度,然后在加载图像后删除样式属性。我下面的内容在 70% 的情况下有效,另外 30% 的 stye 属性在图像加载之前被删除并且页面跳转仍然存在。有没有办法在图像完全加载后才删除样式属性?或者设置延迟什么的?我是 JS 和 Ajax 菜鸟,所以请温柔一点。

        (function($){
        $(function(){
            var $form   = $('#customize'), // Search form
                $target = $('.results'), // Results container
                rp      = 'product_search/results_only_ajax'; // Template for results only

            // Function to execute on success
            var success = function(data, status, xhr) {
                $target.html(data);
                $('.loading').html('<p></p>');
                // Remove style
                $('.results').removeAttr("style");
            };

            // Hijack the form on submit
            $form.submit(function(){

                // Tell target we're loading
                $('.loading').html('<p>Loading...</p>');
                // get height of container, and set height
                currentHeight = $('.results').outerHeight();
                $('.results').css("height", currentHeight);

                // Add custom result page to data
                var data = $form.serialize()
                         + '&result_page=' + rp;

                // Perform the ajax call
                $.ajax({
                    type: 'POST',
                    url: $form.attr('action'),
                    data: data,
                    success: success,
                    dataType: 'html'
                });

                // Don't submit the form afterwards
                return false;
            });
        });
    })(jQuery);

编辑:

            // Function to execute on success
            var success = function(data, status, xhr) {
                $target.html(data);
                $('.loading').html('<p></p>');
                // $('.results').removeAttr("style");
                setTimeout(function () {
                    $('.results').removeAttr("style");
                }, 1000);
            };

【问题讨论】:

  • 我在成功功能上添加了一个超时(在我上面的编辑中),这是可行的,但这是最好的方法吗?
  • Infer-On,按照我的方式,有时页面跳转仍然会发生,因为在加载图像之前已经删除了高度样式。设置计时器使图像有足够的机会在删除样式属性之前加载。但我不确定这是否是最好的方法。
  • .html() 理论上是同步的,这意味着你不需要时间。无论如何,我也注意到有时它无法按预期工作。您可以使用 jQuery.load() 异步加载图像并使用 successcallback 添加样式。你也可以试试这个:stackoverflow.com/questions/10673603/… - 它仍然是一个超时功能,但它会检查加载元素的存在,因此如果浏览器花费的时间比预期的长,它也不会中断

标签: javascript jquery ajax


【解决方案1】:

我添加了一个超时,现在可以正常工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-08
    • 1970-01-01
    • 1970-01-01
    • 2020-06-15
    • 1970-01-01
    • 1970-01-01
    • 2016-10-09
    • 1970-01-01
    相关资源
    最近更新 更多