создание кликабельного изображения и применение к нему слушателя события клика - PullRequest
0 голосов
/ 13 октября 2018

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

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

Следующий код, который у меня есть:

HTML5

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>About</title>
    <link rel="stylesheet" type="text/css" href="Styles.css" />
    <script src="Scripts/jquery-3.3.1.intellisense.js"></script>
    <script src="Scripts/jquery-3.3.1.js"></script>
</head>
<body>
    <header>
        <img src="Images/Logo.png" id="logoheader" class="logo" alt="CompTech Logo" />
        <h1 id="title">
            CompTech Inc. 2018 Conference
        </h1>
    </header>
    <nav id="navbar">
        <span>
            <a href="Indedx.html">Home</a>
            <a href="Program.html">Program</a>
            <a href="About.html" class="inactivelink">About</a>
            <a href="Registration.html">Registration</a>
            <a href="Sitemap.html">Sitemap</a>
        </span>
    </nav>

    <main>
        <div id="container">
            <article>
                <section id="personnel">
                    <h2>Personnel</h2>
                    <p>Find out more about the staff that you will be meeting at the event</p>
                    <button id="jim" class="profile"></button>
                    <button id="arcturus" class="profile"></button>
                    <button id="sarah" class="profile"></button>
                    <button id="jaina" class="profile"></button>
                    <div id="descriptioncontainer">
                        <p id="description">Click on the portraits above to learn more about each member of the organisation. The description will appear here and replace this text.</p>
                    </div>
                </section>
            </article>
        </div>
    </main>

    <footer>
        <img src="Images/Logo.png" id="logofooter" class="logo" alt="CompTech Logo" />
        <p>
            <strong>&#169; Copyright CompTech Inc.</strong> <br />
            <address>123 Knotareal Pl, Sydney CBD, NSW, 2018</address>
            customerservice@comptech.org <br />
            (02) 6258 7412
        </p>
    </footer>

    <script src="About.js"></script>
</body>
</html>

JS

(function clickEvent() {
    var portraits = document.getElementByClassName("profile");

    var counter;
    for (counter = 0; counter < profile.length; counter++) {

        portraits[counter].onclick = function () {

        }
    }
        })

CSS

button.profile.active, button.profile:hover {
    cursor:pointer;
}

.profile {
    width: 250px;
    height: 250px;
    display: inline-block;
    margin-top:2%;
}

#jim {
    background-image: url('Images/JimRaynor.png');
}

#arcturus {
    background-image: url('Images/ArcturusMensk.png');
}

#sarah {
    background-image: url('Images/SarahKerrigan.png');
}

#jaina {
    background-image: url('Images/JainaProudmore.png');
}

#descriptioncontainer {
    border-style:solid;
    border-color:whitesmoke;
    padding:5px;
    min-height:100px;
}

Я включенправильный путь и куда идти отсюда?любая помощь будет оценена

Ответы [ 3 ]

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

Прежде всего, я думаю, что вы должны использовать атрибут type при использовании тега button.И во-вторых, я думаю, что вы можете использовать тег <a> вместо кнопки и вызывать функцию с параметром, который будет содержать имя портрета, чтобы вы могли использовать этот параметр в качестве условия в функции и изменить текст описания.Следуйте этому:

Вот HTML:

<main>
        <div id="container">
            <article>
                <section id="personnel">
                    <h2>Personnel</h2>
                    <p>Find out more about the staff that you will be meeting at the event</p>
                    <a href="javascript:void(0)" onclick="changeDescription(jim)" id="jim" class="profile"></a>
                    <a href="javascript:void(0)" onclick="changeDescription(arcturus)" id="arcturus" class="profile"></a>
                    <a href="javascript:void(0)" onclick="changeDescription(sarah)" id="sarah" class="profile"></a>
                    <a href="javascript:void(0)" onclick="changeDescription(jaina)" id="jaina" class="profile"></a>
                    <div id="descriptioncontainer">
                        <p id="description">Click on the portraits above to learn more about each member of the organisation. The description will appear here and replace this text.</p>
                    </div>
                </section>
            </article>
        </div>
    </main>

Вот функция:

function changeDescription(name) {
 var descriptionTag = document.getElementById('description');

  if(name == 'jim') {
    descriptionTag.innerText = 'This is jim';
  }
  else if(name == 'arcturus') {
    descriptionTag.innerText = 'This is arcturus';
  }
}

Ии так далее. Надеюсь, вы поняли мою точку зрения.

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

@ Math Спасибо за помощь, ваше решение сработало отлично.Однако я продолжал играть с этим и придумал это:

HTML5

<main>
        <div id="container">
            <article>
                <section id="personnel">
                    <h2>Personnel</h2>
                    <p>Find out more about the staff that you will be meeting at the event</p>
                    <img src="Images/ArcturusMensk.png" id="arcturus" class="profile" />
                    <img src="Images/JainaProudmore.png" id="jaina" class="profile"/>
                    <img src="Images/JimRaynor.png" id="jim" class="profile"/>
                    <img src="Images/SarahKerrigan.png" id="sarah" class="profile"/>
                    <p id="description">Click on the portraits above to learn more about each member of the organisation. The description will appear here and replace this text.</p>
                </section>
            </article>
        </div>
    </main>

JS

(function () {
        var profiles = document.getElementsByClassName('profile');
        var counter;
        var description;

        for (counter = 0; counter < profiles.length; counter++) {
            profiles[counter].onclick = function () {
                description = this.id;

                switch (description) {
                    case 'jim':
                        document.getElementById('description').innerHTML = "text";
                        break;
                    case 'arcturus':
                        document.getElementById('description').innerHTML = "text";
                        break;
                    case 'sarah':
                        document.getElementById('description').innerHTML = "text";
                        break;
                    default:
                        document.getElementById('description').innerHTML = "text.";
                        break;
                };
            };
        }
    })();
0 голосов
/ 13 октября 2018

Вы можете назначить идентификатор своему изображению следующим образом:

<img id="myImage" src="Images/Logo.png" id="logoheader" class="logo" alt="CompTech Logo" />

, а затем в javasript вы можете получить элемент по его идентификатору и назначить ему событие щелчка следующим образом:

document.getElementById("myImage").onclick = function() {
//your code here
}

РЕДАКТИРОВАТЬ:

В вашем случае вы также можете заменить все ваши теги <button> на теги <img> источником вашего изображения и вызовомфункция javascript для замены описания путем отправки его в качестве аргумента непосредственно в атрибуты тега img.

Например:

В html, сделайте это для всех ваших профилей:

<img src="Images/JimRaynor.png" onclick="changeDescription('Write the description of Jim HERE')"/>

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

function changeDescription(description) {
document.getElementById('description').innerHTML = description;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...