Karma 基本用法

安装

1
2
$ npm install karma --save-dev
$ npm install karma-jasmine karma-chrome-launcher jasmine-core --save-dev

生成配置文件

1
$ node ./node_modules/karma/bin/karma init karma.conf.js

运行

1
$ node ./node_modules/karma/bin/karma start karma.conf.js

评论和共享

1
2
3
4
5
6
7
8
<div class="box">

<div id="oDiv">
<a href="javascript:;">点我</a>
<span id="hh">awd</span>
</div>

</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// ============ 简单的事件委托
function delegateEvent(interfaceEle, selector, type, fn) {
if(interfaceEle.addEventListener){
interfaceEle.addEventListener(type, eventfn);
}else{
interfaceEle.attachEvent("on"+type, eventfn);
}

function eventfn(e){
var e = e || window.event;
var target = e.target || e.srcElement;
if (matchSelector(target, selector)) {
if(fn) {
fn.call(target, e);
}
}
}
}
/**
* only support #id, tagName, .className
* and it's simple single, no combination
*/
function matchSelector(ele, selector) {
// if use id
if (selector.charAt(0) === '#') {
return ele.id === selector.slice(1);
}
// if use class
if (selector.charAt(0) === '.') {
return (' ' + ele.className + ' ').indexOf(' ' + selector.slice(1) + ' ') != -1;
}
// if use tagName
return ele.tagName.toLowerCase() === selector.toLowerCase();
}

//调用
var odiv = document.getElementById('oDiv');
delegateEvent(odiv,'a','click',function(){
alert('1');
})
delegateEvent(odiv,'#hh','click',function(){
alert('2');
})

评论和共享

解决 ListView 不能撑开问题

方法一

动态的计算 ListView 实际高度,使其可以撑开父元素

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
* 动态设置 ListView 高度,使其可以撑开父元素
*/
private void setListViewHeight(){
if (listAdapter == null) {
return;
}

int listViewHeight = 0;
for(int i=0; i<listAdapter.getCount(); i++){
View temp = listAdapter.getView(i,null, listView);
temp.measure(0,0);
listViewHeight += temp.getMeasuredHeight();
}

LayoutParams layoutParams = this.listView.getLayoutParams();
layoutParams.height = listViewHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(layoutParams);
listView.setFocusable(false);
}

方法二

继承 ListView 复写 onMeasure 方法,使其不能滚动。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ListView;

public class NoScrollListview extends ListView {

public NoScrollListview(Context context, AttributeSet attrs) {
super(context, attrs);
}

/**
* 设置不滚动
*/
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);

}
}

解决撑开 ListView 后滚动位置不正常问题

重新计算元素大小后将滚动条移到最上面有些时候并不能成功,正确的做法是在 ListView 注册后将其焦点取消掉。

1
listView.setFocusable(false);

评论和共享

  • 第 1 页 共 1 页
作者的图片

Archie Shi

Nothing to say


Front-End Development Engineer