Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

实现一个Select控件 #4

Open
errorrik opened this issue Dec 12, 2014 · 0 comments
Open

实现一个Select控件 #4

errorrik opened this issue Dec 12, 2014 · 0 comments

Comments

@errorrik
Copy link

实现一个模拟的下拉表单控件:Select。功能要求如下:

说明:

  1. 下拉表单的用户行为类似原生的select,可以参考 http://errorrik.com/er/src/test/esui/select.html
  2. options数据为复合数据:用户行为选中某项时,主区域应显示其text属性的内容;使用setValue方法设置值时,通过value属性对应
  3. 初始化下拉表单时,选中第一项,并且主区域应显示第一项的内容
  4. Select控件需要支持change事件,当用户选择了某项时,触发change事件。eventArg请随意设计,符合常识就行。事件的绑定在参考代码中已经做好,只要在用户行为时正确触发就能做到
  5. 页面上有个select[id=rel]的原始表单,要求其选择的变化能实时同步到模拟的sexSelect中。select[id=rel]的事件在参考代码中已经绑定好,只要正确实现setValue方法就能做到

小提示:

  1. 模拟的Select,需要一个额外的层,并且是绝对定位(position:absolute)的。这个层需要在render中创建,并append到页面中。在主区域点击的时候,需要控制这个层的显示隐藏,并且显示的时候,需要指定位置。
  2. 点击页面其他位置的时候,层如果是打开的,需要关闭。这个行为需要给document绑事件。

参考 index.html 代码

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<link rel="stylesheet" href="index.css" />
</head>

<body>
<h2 id="info"></h2>
<div id="sex-select"></div>
<div id="career-select"></div>

<select id="rel">
    <option value="1"></option>
    <option value="0"></option>
</select>

<script src="Select.js"></script>
<script>
var sexOptions = [ 
    {text: 'male', value: 1}, 
    {text: 'female', value: 0} 
];

var careerOptions = [ 
    {text: 'ue', value: 1},
    {text: 'fe', value: 2},
    {text: 'rd', value: 3},
    {text: 'qa', value: 4},
    {text: 'op', value: 5},
    {text: 'pm', value: 6} 
];
var sexSelect = new Select( sexOptions, document.getElementById('sex-select') );
var careerSelect = new Select( careerOptions, document.getElementById('career-select') );

sexSelect.render();
careerSelect.render();

sexSelect.onchange = careerSelect.onchange = function () {
    document.getElementById('info').innerHTML = sexSelect.getValue() + ',' + careerSelect.getValue();
};

document.getElementById('rel').onchange = function () {
    sexSelect.setValue(this.value);
};
</script>
</body>
</html>

参考 Select.js 代码

function Select(options, main) {
    // 实现Select组件的构造函数
    // 在这里初始化一些信息
    this.options = options || [];
    this.main = main;
    // ......
}

Select.prototype.render = function () {
    // 实现Select组件的渲染
    // 在这里创建select相关的dom,append到页面中,并绑定相关行为
};

Select.prototype.setValue = function (value) {
    // 实现setValue方法,使JS能够更改Select当前选中的值
};

Select.prototype.getValue = function () {
    // 实现setValue方法,使JS能够获取Select当前选中的值
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant