Общая функция JavaScript для нескольких типов ввода = текст и тип ввода = цвет - PullRequest
0 голосов
/ 01 мая 2018

В моем теге body у меня есть два типа ввода (текст и цвет). Это работает так,

  1. Если вы укажете шестнадцатеричное значение цвета в inputText, inputColor автоматически изменится на этот цвет.
  2. Если вы выберете цвет с помощью colorPicker, inputText будет автоматически изменить значение colorHex, которое вы выбрали.

Ниже работает код

<body>

<input type="text" id="txtColor">
<input type="color" id="colColor" >
<script>

document.getElementById("txtColor").onblur = function() {myFunction1()};
document.getElementById("colColor").onchange = function() {myFunction2()};

function myFunction1() {
    //alert("Input field lost focus.");
    var txtColor = document.getElementById("txtColor").value;
	
    document.getElementById("txtColor").nextElementSibling.value = txtColor;
   
//    document.getElementById("colColor").value = txtColor;
}

function myFunction2() {
    //alert("Input field lost focus.");
    var colColor = document.getElementById("colColor").value;
    document.getElementById("colColor").previousElementSibling.value = colColor;
    
    //document.getElementById("txtColor").value = colColor;
}


</script>

</body>

Что я пытаюсь сделать, так это то, что у меня есть таблица с несколькими строками из вышеуказанной пары (inputText & inputColor). Он должен функционировать аналогично вышеуказанному. Я пытаюсь с getElementsByClassName, имеющим общее имя класса для inputText и inputColor, чтобы он обновлял родного брата с помощью значения hexColor или цвета.

Это мой текущий код, он не работает. В настоящее время появляется ошибка "Uncaught TypeError: txtColorClass.addEventListener не является функцией"

<body>

<table>
    <tr>
        <td>
            <input type="text" id="txtColor0" class="txtColorClass">
            <input type="color" id="colColor0" >            
        </td>
    </tr>
    <tr>
        <td>
            <input type="text" id="txtColor1" class="txtColorClass">
            <input type="color" id="colColor1" >            
        </td>
    </tr>
    <tr>
        <td>
            <input type="text" id="txtColor2" class="txtColorClass">
            <input type="color" id="colColor2" >            
        </td>
    </tr>    
</table>

<script>

var txtColorClass = document.getElementsByClassName("txtColorClass");
txtColorClass.addEventListener("blur", function( event ) {
  //event.target.style.background = "pink";    
  var txtColor = event.target.value;	
  event.target.nextElementSibling.value = txtColor;
  
}, true);


//document.getElementById("txtColor").onblur = function() {myFunction1()};
document.getElementById("colColor").onchange = function() {myFunction2()};

function myFunction1() {
    //alert("Input field lost focus.");
    var txtColor = document.getElementById("txtColor").value;
	
    document.getElementById("txtColor").nextElementSibling.value = txtColor;
   
//    document.getElementById("colColor").value = txtColor;
}

function myFunction2() {
    //alert("Input field lost focus.");
    var colColor = document.getElementById("colColor").value;
    document.getElementById("colColor").previousElementSibling.value = colColor;
    
    //document.getElementById("txtColor").value = colColor;
}


</script>

</body>

Ответы [ 2 ]

0 голосов
/ 01 мая 2018

Большое спасибо NewToJS с вашим намеком, я смог решить эту проблему.

<body>

<table>
    <tr>
        <td>
            <input type="text" id="txtColor0" class="txtColorClass">
            <input type="color" id="colColor0" class="colColorClass">
        </td>
    </tr>
    <tr>
        <td>
            <input type="text" id="txtColor1" class="txtColorClass">
            <input type="color" id="colColor1" class="colColorClass">
        </td>
    </tr>
    <tr>
        <td>
            <input type="text" id="txtColor2" class="txtColorClass">
            <input type="color" id="colColor2" class="colColorClass">
        </td>
    </tr>    
</table>

<script>

var txtColorClass = document.getElementsByClassName("txtColorClass");
var colColorClass = document.getElementsByClassName("colColorClass");

for(let i = 0; i < txtColorClass.length; i++) {
    txtColorClass[i].addEventListener("blur", function() {
        var txtColor = event.target.value;	
        event.target.nextElementSibling.value = txtColor;
  })
}

for(let i = 0; i < colColorClass.length; i++) {
    colColorClass[i].addEventListener("change", function() {
        var colColor = event.target.value;	
        event.target.previousElementSibling.value = colColor;
  })
}

</script>

</body>
0 голосов
/ 01 мая 2018

Проверьте ниже фрагмент

Есть много возможных способов сделать это. Ниже приведен один из возможных способов. И вы можете легко сделать это с помощью jquery.

var txtColorClass = document.getElementsByClassName("txtColorClass");

for(var i = 0; i < txtColorClass.length; i++)
{
   txtColorClass.item(i).addEventListener("blur", function( event ) {
  //event.target.style.background = "pink";    
  var txtColor = event.target.value;	
  event.target.nextElementSibling.value = txtColor;
  
}, true);

}


var colColorClass = document.getElementsByClassName("colColor");


function myFunction1() {
    //alert("Input field lost focus.");
    var txtColor = document.getElementById("txtColor").value;
	
    document.getElementById("txtColor").nextElementSibling.value = txtColor;
   
//    document.getElementById("colColor").value = txtColor;
}

function myFunction2(colColorBox) {
    //alert("Input field lost focus.");
    var colColor = colColorBox.value;
    colColorBox.previousElementSibling.value = colColor;
    
    //document.getElementById("txtColor").value = colColor;
}
<body>

<table>
    <tr>
        <td>
            <input type="text" id="txtColor0" class="txtColorClass">
            <input type="color" id="colColor0" class="colColor" onchange="myFunction2(this)">            
        </td>
    </tr>
    <tr>
        <td>
            <input type="text" id="txtColor1" class="txtColorClass">
            <input type="color" id="colColor1" class="colColor" onchange="myFunction2(this)">            
        </td>
    </tr>
    <tr>
        <td>
            <input type="text" id="txtColor2" class="txtColorClass">
            <input type="color" id="colColor2" class="colColor" onchange="myFunction2(this)">            
        </td>
    </tr>    
</table>

</body>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...