我正在尝试在移动设备(ios + android)上实现这样的效果: http://i.imgur.com/6zaTdRd.png
当前选中的文本框有蓝色图标+下划线
所以我的框架不支持对任何类型的位图图像进行灰度缩放,因此我需要在两个图像之间交换以实现此效果。
我目前的实现是这样的:
请注意钛合金 MVC 框架的这一点,但我猜基本逻辑应该是相似的。
我监听模糊/聚焦事件以切换当前图像
$.firstNameField.addEventListener('focus', function(e){
swapImages($.firstNameField.getParent());
});
$.lastNameField.addEventListener('focus', function(e){
swapImages($.lastNameField.getParent());
});
然后我像这样交换图像:
/**
* Swaps between the images (..._0 and ..._1) of an ImageView nested in a
TableRow
* ..._0 Greyscale image
* ..._0 Colour image
* @param e current TableViewRow
*/
function swapImages(e){
var imagePathSplit = (e.children[0].image).split('_');
var newImagePath = null;
if(imagePathSplit[1] == "0.png")
newImagePath = imagePathSplit[0] + "_1.png";
else
newImagePath = imagePathSplit[0] + "_0.png";
e.children[0].image = newImagePath;
return;
}
这看起来不太好,特别是因为我需要更多具有此功能的字段,我还想在字段之间实现制表符(使用 Return 键 = NEXT),这将进一步增加每个字段的 1 个事件监听器.
如何理想地完成这样的事情?我可以想到一种方法,只需以数组形式在代码中创建字段,这应该有助于简化问题(不再为父/子寻找太多,但这最终仍会使用相当多的监听器进行切换,对吗?
编辑:忘记添加我如何设置 textFields:
<TableView id="paypalTable">
<TableViewSection>
<TableViewRow id="firstNameView" class="tableRow">
<ImageView id="firstNameIcon" class="textFieldIcon"/>
<TextField id="firstNameField" class="textField"/>
</TableViewRow>
最佳答案
我在我的一个项目中尝试过类似的东西。尽管我有一个 Alloy 项目,但我必须使用经典方法来获得我想要的行为。
在我的 Controller 中:
var textFields = [];
var yourTextFieldsArray = [];
for (var i = 0; i < yourTextFieldsArray; i++) {
//Set the selected state to false initially. Maybe you need another command for it.
textFieldIsSelected[i] = false;
//create your new view
textFields[i] = Ti.UI.createView({
top : topValues[i],
width : Titanium.UI.FILL,
height : height,
id : i + 1,
touchEnabled : true
});
textFields[i].addEventListener('click', function(e) {
//Check the source id
if (e.source.id - 1 > -1) {
//use your function swapImages(e.source.id). Notice the slightly different parameter since you do not need the complete event.
swapImages(e.source.id);
}
}
function swapImages(id){
//Check the the path variable as you did
var imagePathSplit = (textFields[i-1].image).split('_');
var newImagePath = null;
if(imagePathSplit[1] == "0.png")
newImagePath = imagePathSplit[0] + "_1.png";
else
newImagePath = imagePathSplit[0] + "_0.png";
textFields[i-1].image = newImagePath;
}
这种方法让您可以为每个属性使用相同的事件监听器。
请注意我的 ID 从 1 开始,不是 从 0 开始。这是因为我必须为图像实现这样的行为,而 ImageView 不接受 id=0
.我的猜测是 TextViews 也不会这样做,所以你应该坚持下去。进一步注意,您需要递减 id 以获取 textFields
数组中的相应对象。否则你会得到一个越界错误。
您应该为 NEXT 事件再创建一个事件监听器。实现方式与第一个eventListener相同。也许代码并不完美,因为我是凭内存写的。如果还有任何问题,请随时在评论中提问。
关于javascript - 突出显示当前选定的文本字段 - 最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28972721/