Кнопка нажала изменить цвет - PullRequest
0 голосов
/ 29 октября 2018

Так что немного застрял здесь, у меня есть несколько кнопок, которые я хочу сделать отдельные действия. Например, если кто-то щелкает зеленым цветом, он меняет цвет текста абзаца на зеленый, я выполнил первый, но, похоже, не могу работать с другими, как правильно это сделать?

//JS:

    function myFunction() {
    
      var p = document.getElementById("paragraph"); // get the paragraph
        document.getElementById("paragraph").style.color = "green";
    
      var p = document.getElementById("paragraph"); // get the paragraph
        document.getElementById("Bluecolour").style.color = "blue";
    }
    <!doctype html>
    <html lang="en">
    <head>
      <title> Change Paratext </title>
      <meta charset="utf-8">
      <script src="task2.js"></script>
      <style>
      #paragraph {
        padding: 10px;
        margin-bottom: 10px;
        background-color: silver;
        border: 1px dashed black;
        width: 90%; /* you can adjust this on Firefox if needed */
        height: 200px;
        overflow: hidden;
        margin-top: 10px;
      }
      </style>
    </head>
    <body>
    <h1> Ali Rizwan </h1>
    <p id="paragraph"> Box changes text based on what colour is clicked <br>
    <!-- add your buttons here. All buttons should be in one paragraph -->
    </p>
    
    <p id="buttons">
    <button type="button" onclick="myFunction()" id="GreenColour">Green</button><!-- Changes text to Green -->
    <button type="button" onclick="myFunction()" id="Bluecolour">Blue</button><!-- Changes text to Blue -->
    <button type="button" onclick="myFunction()" id="Mono">Mono</button> <!-- Changes text to Mono -->
    <button type="button" onclick="myFunction()" id="Sans Serif">Sans Serif</button> <!-- Changes text to Sans Serif -->
    <button type="button" onclick="myFunction()" id="Serif">Serif</button> <!-- Changes text to Serif -->
    <button type="button" onclick="myFunction()" id="SizeAdd">Size++</button> <!-- This button increases size by 1 every time its clicked -->
    <button type="button"onclick="myFunction()" id="SizeMinus">Size--</button> <!-- This button decreases size by 1 every time its clicked -->
    
    </p>
    </div>
    </body>
    </html>

Ответы [ 10 ]

0 голосов
/ 29 октября 2018

Итак, с вашей помощью и другими, кто видел это, я узнал об этом, по сути, имя кнопки onclick можно использовать в JS, чтобы изменить цвет текста, определить идентификатор кнопки, создать переменную, а затем JS по умолчанию, чтобы изменить цвет абзаца. ,

HTML:

   <!doctype html>
<html lang="en">
<head>
  <title> Change Paratext </title>
  <meta charset="utf-8">
  <script src="task2.js"></script>
  <style>
  #paragraph {
    padding: 10px;
    margin-bottom: 10px;
    background-color: silver;
    border: 1px dashed black;
    width: 90%; /* you can adjust this on Firefox if needed */
    height: 100px;
    overflow: hidden;
    margin-top: 10px;
  }
  </style>
</head>
<body>
<h1> Ali Rizwan </h1>
<p id="paragraph"> Box changes text based on what colour is clicked <br>
<!-- add your buttons here. All buttons should be in one paragraph -->
</p>

<p id="buttons">
<button type="button" onclick="green()">Green</button><!-- Changes text to Green -->
<button type="button" onclick="blue()">Blue</button><!-- Changes text to Blue -->
<button type="button" onclick="mono()">Mono</button><!-- Changes text to monospace-->
<button type="button" onclick="sansserif()">Sans Serif</button><!-- Changes text to Sans Serif-->
<button type="button" onclick="serif()">Serif</button><!-- Changes text to Serif-->
</p>
</div>
</body>
</html>

JS:

function blue() {
  var p = document.getElementById("paragraph"); // get the paragraph
  p.style.color= 'blue'
}

function green() {
  var p = document.getElementById("paragraph"); // get the paragraph
  p.style.color= 'green'
}

function mono(){
  var p = document.getElementById("paragraph"); // get the paragraph
  p.style.fontFamily = 'monospace'
}

function sansserif(){
  var p = document.getElementById("paragraph"); // get the paragraph
  p.style.fontFamily = 'sans-serif'
}

function serif(){
  var p = document.getElementById("paragraph"); // get the paragraph
  p.style.fontFamily = 'serif'
}
0 голосов
/ 29 октября 2018

Прежде всего, по причинам кэширования, лучше всего использовать внешний CSS и JavaScript. Просто убедитесь, что вы меняете имена файлов CSS и JavaScript при каждом обновлении кода при запуске. Кроме того, рекомендуется разделять HTML, CSS и JavaScript.

Вот код, показывающий, как изменить цвета. Должно быть легко увидеть, что вы можете просто изменить аргумент paraColor, следуя шаблону дизайна ниже, чтобы получить результаты, которые вы ищете.

//<![CDATA[
/* js/external.js */
var doc, bod, htm, M, I, S, Q, paraColor; // for use on other loads
addEventListener('load', function(){
doc = document; bod = doc.body; htm = doc.documentElement;
M = function(tag){
  return doc.createElement(tag);
}
I = function(id){
  return doc.getElementById(id);
}
S = function(selector, within){
  var w = within || doc;
  return w.querySelector(selector);
}
Q = function(selector, within){
  var w = within || doc;
  return w.querySelectorAll(selector);
}
var para = I('paragraph'), pS = para.style;
paraColor = function(color){
  pS.color = color;
}
I('greenColor').addEventListener('click', function(){
  paraColor('green');
});
I('blueColor').addEventListener('click', function(){
  paraColor('blue');
});
}); // load end
//]]>
/* css/external.css */
html,body{
  padding:0; margin:0;
}
.main{
  width:980px; margin:0 auto;
}
#paragraph{
  height:100px; background-color:silver; padding:10px; border:1px dashed black;
  margin:10px 0; overflow:hidden;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
  <head>
    <meta http-equiv='content-type' content='text/html;charset=utf-8' />
    <meta name='viewport' content='width=device-width, height=device-height, initial-scale:1, user-scalable=no' />
    <title>Paratext</title>
    <link type='text/css' rel='stylesheet' href='css/external.css' />
    <script src='js/external.js'></script>
  </head>
<body>
  <div class='main'>
    <h1>Ali Rizwan</h1>
    <p id='paragraph'>Box changes text based on what color is clicked</p>
    <p id='buttons'>
      <input type='button' id='greenColor' value='Green' />
      <input type='button' id='blueColor' value='Blue' />
    </p>
  </div>
</body>
</html>
0 голосов
/ 29 октября 2018

Самый простой способ - создать функцию с параметром типа myFunction(name, value)

var fontSize = 12;

function myFunction(name, value) {
  var p = document.getElementById("paragraph");
  if (value == 'SizeAdd') {
    fontSize += 2;
    value = fontSize + 'px';
  }
  if (value == 'SizeMinus') {
    fontSize -= 2;
    value = fontSize + 'px';
  }
  p.style[name] = value;
}
<p id="paragraph"> Box changes text based on what colour is clicked <br>
  <!-- add your buttons here. All buttons should be in one paragraph -->
</p>

<p id="buttons">
  <button type="button" onclick="myFunction('color', 'green')">Green</button>
  <button type="button" onclick="myFunction('color', 'blue')">Blue</button>
  <button type="button" onclick="myFunction('fontFamily', 'Mono')">Mono</button>
  <button type="button" onclick="myFunction('fontFamily', 'Sans-Serif')">Sans Serif</button>
  <button type="button" onclick="myFunction('fontFamily', 'Serif')">Serif</button>
  <button type="button" onclick="myFunction('fontSize', 'SizeAdd')">Size++</button>
  <button type="button" onclick="myFunction('fontSize', 'SizeMinus')">Size--</button>
</p>
0 голосов
/ 29 октября 2018

Вы можете разделить логику на разные функции и передать им значения в качестве аргументов:

const paragraph = document.getElementById("paragraph");
let fontSize = 1;
function setStyle(style, value) {
  paragraph.style[style] = value;
}

function incrementSize(value) {
  fontSize += value
  paragraph.style.fontSize = `${fontSize}em` ;
}
<!doctype html>
<html lang="en">
<head>
  <title> Change Paratext </title>
  <meta charset="utf-8">
  <script src="task2.js"></script>
  <style>
  #paragraph {
    padding: 10px;
    margin-bottom: 10px;
    background-color: silver;
    border: 1px dashed black;
    width: 90%; /* you can adjust this on Firefox if needed */
    height: 200px;
    overflow: hidden;
    margin-top: 10px;
  }
  </style>
</head>
<body>
<h1> Ali Rizwan </h1>
<p id="paragraph"> Box changes text based on what colour is clicked <br>
<!-- add your buttons here. All buttons should be in one paragraph -->
</p>

<p id="buttons">
<button type="button" onclick="setStyle('color', 'green')" id="GreenColour">Green</button><!-- Changes text to Green -->
<button type="button" onclick="setStyle('color', 'blue')" id="Bluecolour">Blue</button><!-- Changes text to Blue -->
<button type="button" onclick="setStyle('font-family', 'monospace')" id="Mono">Mono</button> <!-- Changes text to Mono -->
<button type="button" onclick="setStyle('font-family', 'sans-serif')" id="Sans Serif">Sans Serif</button> <!-- Changes text to Sans Serif -->
<button type="button" onclick="setStyle('font-family', 'serif')" id="Serif">Serif</button> <!-- Changes text to Serif -->
<button type="button" onclick="incrementSize(+0.1)" id="SizeAdd">Size++</button> <!-- This button increases size by 1 every time its clicked -->
<button type="button"onclick="incrementSize(-0.1)" id="SizeMinus">Size--</button> <!-- This button decreases size by 1 every time its clicked -->

</p>
</div>
</body>
</html>
0 голосов
/ 29 октября 2018

Обновлен код с использованием SWITCH case

//JS:

    function myFunction(btnColor) {
    var p = document.getElementById("paragraph"); // get the paragraph
    switch(btnColor){
    case 'green':
    document.getElementById("paragraph").style.color = "green";
    break;
     case 'blue':
    document.getElementById("paragraph").style.color = "blue";
    break;
    case 'mono':
    document.getElementById("paragraph").style.color = "mono";
    break;
    case 'sansserif':
    document.getElementById("paragraph").style.fontFamily = "Sans Serif";
    break;
    case 'serif':
    document.getElementById("paragraph").style.fontFamily = "serif";
    break;
    case 'sizeadd':
    var el = document.getElementById('paragraph');
var style = window.getComputedStyle(el, null).getPropertyValue('font-size');
var fontSize = parseFloat(style); 
el.style.fontSize = (fontSize + 1) + 'px';
    document.getElementById("paragraph").style.fontSize = "serif";
    break;
    case 'sizeminus':
    var el = document.getElementById('paragraph');
var style = window.getComputedStyle(el, null).getPropertyValue('font-size');
var fontSize = parseFloat(style); 
el.style.fontSize = (fontSize - 1) + 'px';
    break;
    }
      
    }
 
 #paragraph {
        padding: 10px;
        margin-bottom: 10px;
        background-color: silver;
        border: 1px dashed black;
        width: 90%; /* you can adjust this on Firefox if needed */
        height: 20px;
        overflow: hidden;
        margin-top: 10px;
      }
   <!doctype html>
    <html lang="en">
    <body>
    <h1> Ali Rizwan </h1>
    <p id="paragraph"> Box changes text based on what colour is clicked <br>
    <!-- add your buttons here. All buttons should be in one paragraph -->
    </p>
    
    <p id="buttons">
    <button type="button" onclick="myFunction('green')" id="GreenColour">Green</button><!-- Changes text to Green -->
    <button type="button" onclick="myFunction('blue')" id="Bluecolour">Blue</button><!-- Changes text to Blue -->
    <button type="button" onclick="myFunction('mono')" id="Mono">Mono</button> <!-- Changes text to Mono -->
    <button type="button" onclick="myFunction('sansserif')" id="Sans Serif">Sans Serif</button> <!-- Changes text to Sans Serif -->
    <button type="button" onclick="myFunction('serif')" id="Serif">Serif</button> <!-- Changes text to Serif -->
    <button type="button" onclick="myFunction('sizeadd')" id="SizeAdd">Size++</button> <!-- This button increases size by 1 every time its clicked -->
    <button type="button"onclick="myFunction('sizeminus')" id="SizeMinus">Size--</button> <!-- This button decreases size by 1 every time its clicked -->
    
    </p>
    </div>
    </body>
    </html>
0 голосов
/ 29 октября 2018

Вы можете сделать это так

<button type="button" onclick="myFunction()" id="GreenColour" c_name="green">Green</button><!-- Changes text to Green -->
<button type="button" onclick="myFunction()" id="Bluecolour" c_name="blue">Blue</button><!-- Changes text to Blue -->

function myFunction(evn) {
    var color = event.currentTarget.getAttribute('c_name');
    document.getElementById("paragraph").style.color = color;
   event.currentTarget.style.color = color;
}

установить имя цвета в div в качестве атрибута, прочитать этот атрибут в вызывающей функции и использовать его.

0 голосов
/ 29 октября 2018

Есть разные способы сделать это,

  1. Назовите отличное имя функции для отдельного идентификатора кнопки и установите фон в соответствии с этим
  2. вызвать ту же функцию, но на этот раз внутри функции передать параметр идентификатора кнопки

    button type = "button" onclick = "myFunction (this.id)" id = "GreenColour"> Зеленый

и функция:

        function myFunction(id) {
         if(id=="GreenColour")
          document.getElementById("paragraph").style.color="green"; // get the paragraph
            //document.getElementById("paragraph").style.color = "green";
         else if(id=="BlueColour")
          document.getElementById("paragraph").style.color=blue; // get the paragraph
          //document.getElementById("Bluecolour").style.color = "blue";
  }
0 голосов
/ 29 октября 2018

Вот полная версия всех работающих кнопок, вы можете использовать регистр переключателя, чтобы вы могли использовать один и тот же код для нескольких кнопок. Я использовал корпус переключателя

function myFunction(actionType,actionValue,currentButton) {
  var increaseDecreaseFactor = 5;
   switch (actionType) {
            case 'color':
                document.getElementById("paragraph").style.color = actionValue;
                 currentButton.style.color = actionValue;
                break; 
                case 'increaseFont':
               
                 txt = document.getElementById("paragraph");
                 style = window.getComputedStyle(txt, null).getPropertyValue('font-size');
                 currentSize = parseFloat(style);
                 txt.style.fontSize = (currentSize + increaseDecreaseFactor) + 'px';
                 
                break;
                 case 'decreaseFont':
               
                 txt = document.getElementById("paragraph");
                 style = window.getComputedStyle(txt, null).getPropertyValue('font-size');
                 currentSize = parseFloat(style);
                 txt.style.fontSize = (currentSize - increaseDecreaseFactor) + 'px';
                 
                break;
                case 'changeFont':
                  document.getElementById("paragraph").style.fontFamily = actionValue;
                break;
            default:
                break;
        }

 
}
#paragraph {
    padding: 10px;
    margin-bottom: 10px;
    background-color: silver;
    border: 1px dashed black;
    width: 90%; /* you can adjust this on Firefox if needed */
    height: 200px;
    overflow: hidden;
    margin-top: 10px;
  }
<h1> Ali Rizwan </h1>
<p id="paragraph"> Box changes text based on what colour is clicked <br>
<!-- add your buttons here. All buttons should be in one paragraph -->
</p>

<p id="buttons">
<button type="button" onclick="myFunction('color','green',this)" id="GreenColour">Green</button><!-- Changes text to Green -->
<button type="button" onclick="myFunction('color','blue',this)" id="Bluecolour">Blue</button><!-- Changes text to Blue -->
<button type="button" onclick="myFunction('increaseFont','size++',this)" id="SizeAdd">Size++</button> <!-- This button increases size by 1 every time its clicked -->
<button type="button"onclick="myFunction('decreaseFont','size--',this)" id="SizeMinus">Size--</button> <!-- This button decreases size by 1 every time its clicked -->
<button type="button" onclick="myFunction('changeFont','monospace',this)" id="Mono">Mono</button> <!-- Changes text to Mono -->
<button type="button" onclick="myFunction('changeFont','Sans-Serif',this)" id="Sans Serif">Sans Serif</button> <!-- Changes text to Sans Serif -->
<button type="button" onclick="myFunction('changeFont','Serif',this)" id="Serif">Serif</button> <!-- Changes text to Serif -->


</p>
</div>
0 голосов
/ 29 октября 2018

Ваш myFunction() не знает, что ему нужно делать, когда его вызывают.

Попробуйте этот код начального уровня, просто объявите несколько функций для изменения цвета текста:

function blue() {
  var p = document.getElementById("paragraph"); // get the paragraph
  p.style.color= 'blue'
}

function green() {
  var p = document.getElementById("paragraph"); // get the paragraph
  p.style.color= 'green'
}

function mono(){
  var p = document.getElementById("paragraph"); // get the paragraph
  p.style.fontFamily = "monospace"
}
<!doctype html>
<html lang="en">
<head>
  <title> Change Paratext </title>
  <meta charset="utf-8">
  <script src="task2.js"></script>
  <style>
  #paragraph {
    padding: 10px;
    margin-bottom: 10px;
    background-color: silver;
    border: 1px dashed black;
    width: 90%; /* you can adjust this on Firefox if needed */
    height: 100px;
    overflow: hidden;
    margin-top: 10px;
  }
  </style>
</head>
<body>
<h1> Ali Rizwan </h1>
<p id="paragraph"> Box changes text based on what colour is clicked <br>
<!-- add your buttons here. All buttons should be in one paragraph -->
</p>

<p id="buttons">
<button type="button" onclick="green()">Green</button><!-- Changes text to Green -->
<button type="button" onclick="blue()">Blue</button><!-- Changes text to Blue -->
<button type="button" onclick="mono()">Mono</button><!-- Changes text to monospace-->


</p>
</div>
</body>
</html>
0 голосов
/ 29 октября 2018

Сначала добавьте ссылку ниже в вашей головной части.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Вы можете сделать вышеупомянутые вещи следующим образом:

$("button").click(function() {
    var Id = $(this).attr('id');
    if(Id == 'GreenColour'){
        $("#"+Id).css('color','green');
    }elseif(Id == 'Bluecolour'){
        $("#"+Id).css('color','blue');
    }elseif(...){
        .....
    }else(...){
        .....
    }
});

и так далее. Вы можете выполнять различные операции на основе их идентификаторов, если еще.

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