如何将图像预览添加到此jquery脚本?

时间:2011-04-22 23:36:16

标签: jquery image hover preview

我尝试了几种不同的方法将图像悬停预览选项添加到我使用的文件管理器/文件上传脚本中。

我发布下面的脚本。任何帮助表示赞赏。

$(function($){
var optionDefaults = {
    path            : '',
    upload          : false,
    readonly        : false,
    fixedPath       : false,

    baseClass       : 'fmBase',
    folderClass     : 'fmFolder',
    trashClass      : 'fmTrash',
    backClass       : 'fmBack',
    loadingClass    : 'fmLoading',

    highlightClass  : 'ui-state-highlight',
    hoverClass      : 'ui-state-active'
};

$.fn.fileManager = function(settings, pluploadOptions) {
    var mbOptions = $.extend({}, optionDefaults, settings);
    if (!mbOptions.ajaxPath) {
        alert('ajaxPath not specified'); return;
    }
    if (mbOptions.fixedPath) mbOptions.path = mbOptions.fixedPath;

    pluploadOptions = $.extend({url:mbOptions.ajaxPath,runtimes:'html5,html4'}, pluploadOptions);

    var query = $.extend({},{path:mbOptions.path},mbOptions.get);
    this.each(function () { // swap with getJSON so not duplicating ajax
        var $sel = $(this);
        $.getJSON(mbOptions.ajaxPath, query, function(data, status) {
            $sel.data('result',data);
            $sel.data('options',mbOptions);
            if (status != "success") {
                var msg = "Sorry but there was an error: "+status;
            }
            // process response
            $sel.empty();

            if (!mbOptions.readonly) {
                $sel.append('<div class="path"><b>URL Path:</b> '+data.rootPath+data.path+'</div>');
                if (data.path && !mbOptions.fixedPath) DrawItem($sel,{path:'..',title:'...',type:3});
                DrawItem($sel,{path:'',title:'',type:2});
            }
            if ($(data.files).length == 0) {
              $sel.append('<div style="font-size:12px; margin: 35px 0 0 15px;">No files in this folder</div>');
            }
            $(data.files).each(function () {
                DrawItem($sel,this);
            });
            $sel.append('<div style="clear:both"></div>');
            if (!mbOptions.readonly)
                $sel.append($('<div style="margin:5px">New Folder</div>').button().bind('click',NewFolder));
            if (mbOptions.upload) {
                var ul = $('<div></div>').hide();
                $sel.append($('<div style="margin:5px">Upload Files</div>').button().bind('click',{container:ul},UploadFiles));
                $sel.append(ul);
            }

            // end processing

            $('.'+mbOptions.baseClass,$sel).disableSelection();//bind('selectstart',function () { return false; });
            $('.'+mbOptions.folderClass,$sel).bind('dblclick',ItemDblClick);
            $('.'+mbOptions.backClass,$sel).bind('dblclick',ItemDblClickBack);
        });

        function UploadFiles(event) {
            $(event.data.container).toggle();
            if (plupload && pluploadOptions) {
                if (!$(event.data.container).pluploadQueue) {
                    $(event.data.container).html('Must install Plupload jquery plugin.'); return;
                }
                var opts = pluploadOptions;
                opts.url = opts.url+ (opts.url.indexOf('?') < 0 ? '?' : '&') +'path='+$sel.data('result').path;
                $(event.data.container).pluploadQueue(opts);
                $(event.data.container).pluploadQueue().bind('FileUploaded',function (uploader,file,response) {
                    if (uploader.total.queued == 0) {
                        RefreshView($sel);
                    }
                });
            } else {
                $(event.data.container).html('Must install Plupload.');
            }
        }
        function NewFolder() {
            var path = prompt('Enter Folder Name:');
            if (!path) return;
            if ($sel.data('result').path) path = $sel.data('result').path + '/' + path;
            ReloadFolder($sel, path);
        }
    });


    function FileDropped(event,ui) {
        var from = $(ui.draggable);
        var to = $(this);

        if ($(this).hasClass(mbOptions.trashClass)) {
            if (confirm('Delete "'+from.data('item').title+'"?')) {
                ajaxData = {path:mbOptions.path,'delete':from.data('item').path};
                $.ajax({url:mbOptions.ajaxPath,data:ajaxData,dataType:'script',complete:function() {
                    RefreshView(from.data('item').target);
                }});
            }
        } else {
            return Rename(from.data('item').target,from.data('item').path,to.data('item').path+'/'+from.data('item').path);
        }
    };
    function Rename(view,from,to) {
        ajaxData = {path:mbOptions.path,mFrom:from,mTo:to};
        $.ajax({url:mbOptions.ajaxPath,data:ajaxData,dataType:'script',complete:function() {
            RefreshView(view);
        }});
    }
    function ItemDblClick() {
        var item = $(this).data('item');
        if (item.type != ICONTYPE_FOLDER) return;
        var path = item.path;
        if (item.target.data('result').path) path = item.target.data('result').path + '/' + path;
        ReloadFolder(item.target,path);
    }
    function ItemDblClickBack() {
        var item = $(this).data('item');
        if (item.type != ICONTYPE_BACK) return;
        var path = item.path;
        if (item.target.data('result').path) path = item.target.data('result').path + '/' + path;
        ReloadFolder(item.target,path);
    }
    function RefreshView(target) {
        ReloadFolder(target,target.data('result').path);
    }
    function ReloadFolder(target,path) {
        target.fileManager($.extend({},mbOptions,{path:path}),pluploadOptions);
    };

    var ICONTYPE_FILE = 0;
    var ICONTYPE_FOLDER = 1;
    var ICONTYPE_TRASH = 2;
    var ICONTYPE_BACK = 3;
    function DrawItem(target, item) {
        if (item.type == ICONTYPE_FOLDER && mbOptions.fixedPath) return;

        item.target = $(target);
        item.fullPath = item.target.data('result').rootPath + item.target.data('result').path + '/' + item.path;
        var icon = $('<div title="'+item.title+'"></div>');
        icon.data('item',item);
        icon.addClass(mbOptions.baseClass);

        // set classes
        if (item.type == ICONTYPE_FOLDER)
            icon.addClass(mbOptions.folderClass);
        else if (item.type == ICONTYPE_TRASH)
            icon.addClass(mbOptions.trashClass);
        else if (item.type == ICONTYPE_BACK)
            icon.addClass(mbOptions.backClass);

        // set draggables
        if (!mbOptions.readonly) {
            if (item.type == ICONTYPE_FOLDER || item.type == ICONTYPE_TRASH)
                icon.droppable({tolerance:'intersect',accept:'.'+mbOptions.baseClass,drop:FileDropped,hoverClass:mbOptions.hoverClass,activeClass:mbOptions.highlightClass});
            if (item.type != ICONTYPE_TRASH && item.path != '..')
                icon.draggable({stack:'files',revert:true,zIndex:1000,opacity:0.5,scroll:false});
        }

        if (item.type == ICONTYPE_FILE && item.path.search(/.jpeg|.jpg|.png|.gif|.tif|.tiff/i) > -1) {
            icon.css('background-image','none');
            icon.append('<img style="width:100%;height:100%" src="'+item.fullPath+'">');
        }

        // events
        if (mbOptions.events) {
            $.each(mbOptions.events,function (index,value) {
                icon.bind(index, value);
            });
        }
        icon.data('result',target.data('result'));

        target.append(icon);
        if (!item.path) return;

        //if (mbOptions.readonly) return;

        var ext = item.path.match(/\.[^.\b]*$/i);
        if (ext) ext = ext[0];
        else ext = '';
        var basename = item.path.replace(ext,'');

        var renamebox = $('<input style="position:absolute;left:0px;bottom:0px;right:0px" type="text">')
            .bind('focus',function() { $(this).val(basename); })
            .bind('blur',function() { $(this).hide(); if (item.path == $(this).val()+ext) return; Rename(item.target,item.path,$(this).val()+ext); })
            .bind('keydown',function(event) { if (event.keyCode == '13' || event.keyCode == '27') $(this).blur(); })
            .hide()
            .appendTo(icon);
        var label = $('<div class="label">'+item.title+'</div>')
            .prependTo(icon)//.bind('dblclick',function() {return false;})
            .bind('click',function () {
                if (!mbOptions.readonly) {
                    renamebox.show().focus();
                    return false;
                }
            });
    }

    return $(this);
};

})(jQuery的);

下面是图像预览脚本:

this.imagePreview = function(){ 
/* CONFIG */

    xOffset = 10;
    yOffset = 30;

    // these 2 variable determine popup's distance from the cursor
    // you might want to adjust to get the right result

/* END CONFIG */
$("a.preview").hover(function(e){
    this.t = this.title;
    this.title = "";    
    var c = (this.t != "") ? "<br/>" + this.t : "";
    $("body").append("<p id='preview'><img src='"+ this.href +"' alt='Image preview' />"+ c +"</p>");                                
    $("#preview")
        .css("top",(e.pageY - xOffset) + "px")
        .css("left",(e.pageX + yOffset) + "px")
        .fadeIn("fast");                        
},
function(){
    this.title = this.t;    
    $("#preview").remove();
}); 
$("a.preview").mousemove(function(e){
    $("#preview")
        .css("top",(e.pageY - xOffset) + "px")
        .css("left",(e.pageX + yOffset) + "px");
});         
};// starting the script on page load
$(document).ready(function(){
    imagePreview();
});

我遇到的问题是我必须将预览部分写入文件管理器部分。预览不能作为单独的脚本运行,因为文件管理器脚本使用json / ajax动态写入所有内容。仅供参考,预览脚本在我自己的测试页面中可以正常使用。希望这能澄清我的问题。

1 个答案:

答案 0 :(得分:0)

我发现了我的问题。我从研究jquery中学到的是,悬停是一种促进mouseenter和mouseleave的功能。因此,不要尝试绑定悬停,而是绑定mouseenter和mouseleave事件。

以下是更正前后的代码,以便您查看我的解决方案。

<强> BEFORE

if (item.type == ICONTYPE_FILE && item.path.search(/.jpeg|.jpg|.png|.gif|.tif|.tiff/i) > -1) {
        icon.css('background-image','none');
        icon.append('<img style="width:100%;height:100%" src="'+item.fullPath+'">');
    }

<强> AFTER

if (item.type == ICONTYPE_FILE && item.path.search(/.jpeg|.jpg|.png|.gif|.tif|.tiff/i) > -1) {
            xOffset = 10;
            yOffset = 30; // these 2 variable determine popup's distance from the cursor
            icon.css('background-image','none');
            icon.append($('<img style="width:100%;height:100%" src="'+item.fullPath+'">').bind({
                mouseenter: function(e) {
                // Hover event handler
                $("body").append("<p id='preview'><img src='"+item.fullPath+"' alt='Image preview' /></p>");                                
                $("#preview")
                .css("top",(e.pageY - xOffset) + "px")
                .css("left",(e.pageX + yOffset) + "px")
                .fadeIn("fast");
                },
                mouseleave: function(e) {
                // Hover event handler
                $("#preview").remove();
                }
            }));
        }

备注:您需要将以下css添加到您的某个css文件或您使用的页面中以使其正常工作。

需要CSS

#preview{
position:absolute;
border:1px solid #ccc;
background:#e6e6e6;
padding:5px;
display:none;
color:#fff;
}