当前位置: 代码迷 >> JavaScript >> SharePoint 2013 应用嵌入JavaScript方式实现一个垂直滚动列表
  详细解决方案

SharePoint 2013 应用嵌入JavaScript方式实现一个垂直滚动列表

热度:246   发布时间:2013-01-28 11:49:56.0
SharePoint 2013 使用嵌入JavaScript方式实现一个垂直滚动列表

本文介绍SharePoint 2013(其实也适用于2010,支持JavaScript OM) 中使用嵌入JavaScript方式实现一个垂直滚动列表:

当鼠标进入Item时停止滚动,当鼠标点击对应的Item时,显示对应的Item内容:

实现的大概思路是使用一段较短的JavaScript代码嵌入SharePoint页面,这个JavaScrip片段(可设置相关参数,如列表名,过滤条件等)调用另一个较大的JavaScript文件VerticalScrollingWebPart.js(存储到SharePoint 的SiteAssets/JavaScript中), VerticalScrollingWebPart.js 文件负责使用JavaScript OM 查询后台列表,并根据参数画出一个滚动列表:

嵌入的JavaScript 代码:

<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.0.min.js"></script>
<script type="text/javascript" src="/SiteAssets/Javascript/VerticalScrollingWebPart.js"></script>
<script type="text/javascript">
init_fillScrollableDiv({'web':'',
    'listBaseUrl': 'http://MossHost/Lists/ReadMarkList/DispForm.aspx',
    'listName': 'ReadMarkList',	
	'viewFields':['Title','Body'],    
    'Filter':'<Where> <Or>  <IsNull> <FieldRef Name=\"Expires\" />  </IsNull>  <Geq> <FieldRef Name=\"Expires\"></FieldRef> <Value Type=\"DateTime\"> <Today></Today> </Value> </Geq> </Or> </Where>',
	'viewFieldsStyle':['font-weight:bold','padding:0 0 0 5'],	
	'divID':'myScrollableDiv',
	'divHeight':'250px',
	'divWidth':'500px',	
	'speed':4,
	'linkBack':true});    
</script>

主要参数说明:

1. web,如果取子站点的列表需要填

2. listBaseUrl, 显示list item的地址

3. listName,要读取的list 名称

4.viewFields, 要显示的字段

5.Filter 过滤条件(CAML结构的 Where 子句)

 

VerticalScrollingWebPart.js 代码:

/*
 A vertical scrolling web part for SharePoint 2013
*/
function init_fillScrollableDiv(obj) {
    // Build the div
    var myDivBuffer = [];
    myDivBuffer.push("<div style='vertical-align:top;position:relative;overflow:hidden;cursor:default;height:" + obj.divHeight + ";width:" + obj.divWidth + "'>");
    myDivBuffer.push("<div id='" + obj.divID + "' style='position:relative'></div>");
    myDivBuffer.push("</div>");
    myDivContainer = myDivBuffer.join('');
    document.write(myDivContainer);
    $(document).ready(function () {
        // fillScrollableDiv(obj)
        ExecuteOrDelayUntilScriptLoaded(function () { queryItemsByViewName(obj); }, "sp.js");
        //queryItemsByViewName(obj);
    });
}

function fillScrollableDiv(info, items) {    
    info.animBegin = 0;
    info.animPart = 0;
    if (items.length == -1) alert("An error occured - check the parameters \"listBaseUrl\", \"web\"......");
    var finalBuffer = [];
    var path = info.listBaseUrl;
    var res = new Object();
    res.items = items;
    $.each(res.items, function (i, item) {
        var partBuffer = [];       
        $.each(info.viewFields, function (idx, fin) {
            var style = '';
            var thisVal = (item[fin] == null) ? '' : item[fin];
            if (thisVal.indexOf(';#') > -1) {
                thisVal = thisVal.substring(thisVal.indexOf(';#') + 2);
            }
            if (info.viewFieldsStyle[idx] != undefined) {
                style = " style='" + info.viewFieldsStyle[idx] + "'";
            }
            partBuffer.push("<tr><td" + style + ">" + thisVal + "</td></tr>");
        });
        finalBuffer.push("<hr style='height:1px;color:black' />");
        if (info.linkBack) {
            finalBuffer.push("<table title='Go to item' style='cursor:pointer' ");
            finalBuffer.push("onclick='javascript:location.href=\"" + info.listBaseUrl + "?ID=" + item['ID'] + "&Source=" + location.href + "\"' ");
            finalBuffer.push("cellspacing='0' cellpadding='0'>" + partBuffer.join('') + "</table>");
        } else {
            finalBuffer.push("<table cellspacing='0' cellpadding='0'>" + partBuffer.join('') + "</table>");
        }
    });
    var myContents = finalBuffer.join('');
    // Update the content in the scrollable div
    $("#" + info.divID).html(myContents)
		.mouseenter(function () {
		    var now = new Date();
		    info.animPart += (now - info.animBegin);
		    $(this).stop();
		})
		.mouseleave(function () {
		    $(this).stop();
		    var partScr = parseInt($(this).css('top'));
		    scrollMyDiv(partScr, info);
		});

    // Call scroll function
    scrollMyDiv('', info);
}

function scrollMyDiv(scroll, info) {
    info.animBegin = new Date();
    var myDiv = $("#" + info.divID);
    var ch = myDiv.height();
    var chpHeight = myDiv.parent().height();
    if (scroll == '') {
        var scroll = chpHeight;
    }
    var duration = (ch * (info.speed * 10)) - info.animPart;
    myDiv.css({ 'top': scroll }).animate({ "top": -ch }, duration, 'linear', function () {
        info.animPart = 0;
        scrollMyDiv('', info);
    });
}


// Function to pull items from view
function queryItemsByViewName(info) {
    // ToDo Invoke JavaScript OM query the items
    var ctx = new SP.ClientContext();
    var caml = "<View><Query>" + info.Filter + "</Query></View>";
    var list = ctx.get_web(info.web).get_lists().getByTitle(info.listName);
    var query = new SP.CamlQuery();
    query.set_viewXml(caml);

    // Contact include from viewFields
    var include = "";
    for (i = 0; i < info.viewFields.length; i++) {
        include += info.viewFields[i] + ","
    }

    include += include + 'ID';

    var listItems = list.getItems(query);
    ctx.load(listItems, "Include(" + include + ")")

    var delegateParameter = new Object();
    delegateParameter.info = info;
    delegateParameter.listItems = listItems;
    ctx.executeQueryAsync(
       Function.createDelegate(this, function () { onCamlQuerySuccessedForVerticalScrollingWebpart(delegateParameter); }),
       Function.createDelegate(this, onCamlQueryFailedForVerticalScrollingWebpart)
    );
}

function onCamlQuerySuccessedForVerticalScrollingWebpart(delegateParameter) {    
    var itemsEnumerator = delegateParameter.listItems.getEnumerator();
    var count = delegateParameter.listItems.get_count();
    var items = new Array(count);
    var j=0;
    while (itemsEnumerator.moveNext()) {
        var currentItem = new Object();
        var currentListItem = itemsEnumerator.get_current();       
        for(i=0; i< delegateParameter.info.viewFields.length; i++)
        {
            var fieldName = delegateParameter.info.viewFields[i];
            currentItem[fieldName] = currentListItem.get_item(fieldName);
            if (currentItem[fieldName].length > 200) {
                var index = currentItem[fieldName].indexOf(" ", 200);
                currentItem[fieldName] = currentItem[fieldName].substring(0, index) + "......";
            }
        }

        currentItem['ID'] = currentListItem.get_item('ID');
        items[j] = currentItem;
        j++;
    }

    fillScrollableDiv(delegateParameter.info, items); 
}

function onCamlQueryFailedForVerticalScrollingWebpart(sender, args) {
    alert('Request failed. ' + args.get_message() +
      '\n' + args.get_stackTrace());
}

 

  相关解决方案