如何在浏览器中禁用textarea字段的智能引号?

时间:2017-08-04 14:45:41

标签: javascript ios11

我有一个在浏览器中运行的应用程序,用于比较字符串。字符串与使用iOS11的引号失败进行比较,因为它默认为启用智能引号。 can’t不等于can't

我知道可以在整个设备的设置下禁用智能引号,但我想在textarea级别处理它。

我以为我能够抓住关键按键事件的智能报价,但是iOS正在进行转换,并在后面进行。

textareaText是我的textarea字段中的文本
39是单引号的字符代码 8216是左单智能引用的字符代码
222是引用键的关键代码
e是传递给键盘事件的事件对象

keydown 
    e.keycode -> 222, e.key -> ', key.charCodeAt(0) -> 39 
    textareaText -> empty
keypress
    e.keycode -> 39, e.key -> ', key.charCodeAt(0) -> 39 
    textareaText -> empty
—> character is put in textarea here
keyup (iPad onscreen keyboard)
    e.keycode -> 222, e.key -> ', key.charCodeAt(0) -> 39 
    textareaText -> ’, textareaText.charCodeAt(0) -> 8216 
keyup (iPad external keyboard)
    e.keycode -> 0, e.key -> ', key.charCodeAt(0) -> 39 
    textareaText -> ’, textareaText.charCodeAt(0) -> 8216 

keyup事件认为字符是常规引号,而textarea包含智能引号。

我试过了:

textarea.innerHTML = textarea.innerHTML.replace(/’/,'\'')

但光标会重置到字符串的开头,我不想得到并设置光标位置。

有没有办法在智能报价输入textarea之前进行交换?或者某种方式在textarea级别禁用智能引号?是否有其他解决方案可以解决这个问题?

我的最后一招是在比较它之前替换字符串中的智能引号但我更希望浏览器显示常规引号以与它们输入的内容,它们看到的内容以及它们被检查的内容一致。

2 个答案:

答案 0 :(得分:3)

最简单的方法是将import SwiftUI import PlaygroundSupport struct ContentView: View { // Create the child view to make the save button available inside this view var child = Child() var body: some View { NavigationView { NavigationLink( destination: child.navigationBarItems( // Set the trailing button to the one from the child view. // This is required as this view might be inside a modal // sheet, and we need to add the cancel button as a leading // button: // leading: self.cancelButton trailing: child.saveButton ) ) { Text("Open") } } } } struct Child: View { // Store the value from the textfield @State private var value = "default" // Make this button available inside this view, and inside the parent view. // This makes sure the visibility of this button is always the same. var saveButton: some View { Button(action: save) { Text("Save") } } var body: some View { VStack { // Simple textfield to allow a string to change. TextField("Value", text: $value) // Just for the playground to change the value easily. // Usually it would be chnaged through the keyboard input. Button(action: { self.value = "new value" }) { Text("Update") } } } func save() { // This always displays the default value of the state variable. // Even after the Update button was used and the value did change inside // the textfield. print("\(value)") } } PlaygroundPage.current.setLiveView(ContentView()) 传递给输入元素。这基于WebKit的工作方式:https://github.com/WebKit/webkit/blob/master/Source/WebKit/UIProcess/ios/WKContentViewInteraction.mm#L4852

答案 1 :(得分:0)

我最终在按键事件上使用了document.execCommand。此解决方案也适用于有意义的div。

function checkInput(e) {
  if ((e.which == 39) || (e.which == 8216) || (e.which == 8217)) {
    e.preventDefault();
    document.execCommand('insertText', 0, "'");
  }
}   

var el = document.getElementById('txtIn');
el.addEventListener('keypress', checkInput, false);